The Preg and Pattern Functions (part 4)
There are times when you need PHP to do some weird things, like replacing {{n}} (where n means "any number") with colspan='n'. Now how would you do that using regular expressions and preg_replace? Well, a { is a metacharacter, so it must be written as \{ if you don't want an error. The number inside can written as [0-9]+, for there must be at least one number. In this case, we use # to enclose the regular expression, but we could've used ! or / as well.
Now let's start backwards. Analyze the following line and try to figure out what it does:
Well, we have (\[color=), so the [color= is the $1 part of the pattern (or \\1 part). Then we have [a-zA-Z]+ as $2 of the pattern. And finally we have ] as $3. In other words, if we have something like $text = "[color=red]", preg_replace will output $text = "<span style='color: red;>'".
The preg_split Function
This function splits a string around a pattern. The syntax is as follows:
preg_split(pattern, string, limit (optional), flag (optional));
Once again limit can be omitted. If set to -1, every substring that matches the pattern will be used as a cutting tool for preg_split, and if set to, let's say, three, only the first three substrings that match the pattern will be considered. Examine a script as simple as this one:
$pattern = "#\s*\([0-9]+\)\s*#is";
$names = preg_split($pattern , $str, -1);
$i = 1;
foreach ($names as $print_names)
{
echo "<br />Output $i is: ".$print_names;
$i++;
}
/*
The output will be as follows:
Output 1 is:
Output 2 is: This is Cindy
Output 3 is: This is Brian
Output 4 is: This is Michael
Output 5 is: This is Kimberly
*/
See anything unusual? There's an empty value in the output. Want to fix this? Well, adding the PREG_SPLIT_NO_EMPTY flag prevents preg_split from returning empty values. It is easy to see what preg_split did to $str. Using a pattern, we made it clear that anything following a number enclosed by parentheses had to be a string of its own. Thus we ended up having an array called $names.
Additional Information:
http://www.phpdig.net/ref/rn53re1096.html
http://pa2.php.net/manual/en/function.preg-grep.php
http://www.phpdig.net/ref/rn53re1100.html
http://www.webcheatsheet.com/php/regular_expressions.php>
Return to << Page 3 of this tutorial



