Replacing substrings

The following functions create new strings by replacing substrings:

string ereg_replace(string pattern, string replacement, string source)
string eregi_replace(string pattern, string replacement, string source)

They create a new string by replacing substrings of the source string that match the regular expression pattern with a replacement string. These functions are similar to the str_replace( ) function described earlier in the Section 2.6 section, except that the replaced substrings are identified using a regular expression. Consider the examples:

$source = "The  quick\tbrown\n\tfox jumps";
// prints "The quick brown fox"
echo ereg_replace("[ \t\n]+", " ", $source);
$source = "\xf6 The  quick\tbrown\n\tfox jumps\x88";
// replace all non-printable characters with a space
echo ereg_replace("[^ -~]+", " ", $source);

The second example uses the regular expression "[^ -~]+" to match all characters except those that fall between the space character and the tilde character in the ASCII table. This represents almost all the printable 7-bit characters.

Splitting a string into an array

The following two functions split strings:

array split(string pattern, string source [, integer limit])
array spliti(string pattern, string source [, integer limit])

They split the source string into an array, breaking the string where the matching pattern is found. These functions perform a similar task to the explode( ) function described earlier and as with explode( ), a limit can be specified to determine the maximum number of elements in the array.

The following simple example shows how split( ) can break a sentence into an array of "words" by recognizing any sequence of nonalphabetic characters as separators:

$sentence = "I wonder why he does\nBuzz, buzz, buzz!";
$words = split("[^a-zA-Z]+", $sentence);

When complex patterns aren't needed to break a string into an array, the explode( ) function makes a better choice.