PHP

Extracting multiple values from a string

PHP provides the explode( ) and implode( ) functions, which convert strings to arrays and back to strings:

array explode(string separator, string subject [, integer limit])
string implode(string glue, array pieces)

Explode function

The explode( ) function returns an array of strings created by breaking the subject string at each occurrence of the separator string. The optional integer limit determines the maximum number of elements in the resulting array; when the limit is met, the last element in the array is the remaining unbroken subject string.

Implode function

The implode( ) function returns a string created by joining each element in the array pieces, inserting the string glue between each piece. The following example shows both the implode( ) and explode( ) functions:

Explode and Implde functions examples

$guestList = "Sam Meg Sarah Ben Jess May Adam";
$name = "Fred";
// Check if $name is in the $guestList
if (strpos($guestList, $name) === false)
{
  $guestArray = explode(" ", $guestList);
  sort($guestArray);
  echo "Sorry '$name' is not on the guest list.\n";
  echo "Guest list: " . implode(", ", $guestArray)
}

When the string $name isn't found in the string $guestList using strpos( ), the fragment of code prints a message to indicate that $name isn't contained in the list. The message includes a sorted list of comma-separated names: explode( ) creates an array of guest names that is sorted and then, using implode( ), is converted back into a string with each name separated by a comma and a space. The example prints:

Sorry 'Fred' is not on the guest list.
Guest list: Adam, Ben, Jess, May, Meg, Sam, Sarah

by BrainBellupdated
Advertisement: