Page 129 - Open Soource Technologies 304.indd
P. 129
Unit 5: Strings
They create a new string by replacing substrings of the source string that match the regular Notes
expression pattern with a replacement string. These functions are similar to the str_replace( )
function described earlier in “Replacing Characters and Substrings,” except that the replaced
substrings are identified using a regular expression. Consider the examples:
$source = “The quick red fox jumps”;
// prints “The quick brown fox jumps”
print ereg_replace(“red”, “brown”, $source);
$source = “The quick brown fox jumps
over the lazy dog”;
// replace all whitespace sequences with a single space
// prints “The quick brown fox jumps over the lazy dog”;
print ereg_replace(“[[:space:]]+”, “ “, $source);
You can also use include patterns matched by subexpressions in the replacement string. The
following example replaces all occurrences of uppercase letters with the matched letter surrounded
by <b> and </b> tags:
$source = “The quick red fox jumps over the lazy Dog.”;
// prints “<b>T</b>he quick brown fox jumps over the lazy <b>D</b>og”
print ereg_replace(“([A-Z])”, ‘<b>\1</b>’, $source);
The grouped subexpression is referenced in the replacement string with the \1 sequence. Multiple
subexpressions can be referenced with \2, \3, and so on. The following example uses three
subexpressions to rearrange a data from YYYY-MM-DD format to DD/MM/YYYY format:
$value = “2011-11-12”;
$pattern = ‘^([0-9]{4})-([0-9]{2})-([0-9]{2})$’;
// prints “12/11/2011”
print ereg_replace($pattern, ‘\3/\2/\1’, $value);
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 non-alphabetic characters as separators:
$sentence = “I wonder why he does\nBuzz, buzz, buzz”;
$words = split(“[^a-zA-Z]+”, $sentence);
LOVELY PROFESSIONAL UNIVERSITY 123