Main Content

More than just matching with a regular expression in PHP

Archive - Originally posted on "The Horse's Mouth" - 2012-06-30 16:28:43 - Graham Ellis

There's much more that you can do with regular expressions than just see if a string matches. Here are some examples in PHP, as I was teaching a course in PHP yesterday.

1. You can match, you can match and capture some or all of the matched string, and you can multiple match (and capture) ... see previous article for details.

2. You can split string at a regular exprssion, getting back an array of things that do NOT match;
  $gotten = preg_split("/\s+/",$line);

3. You can match against a whole list (array) of strings, returning the complete matching strings:
  $bigchurch = preg_grep("/Abbey/",$stations);

4. You can match and replace the first match:
  $rv1 = preg_replace('/bury/','flower',$info,1);

5. You can match and replace all matches:
  $rv1 = preg_replace('/bury/','flower',$info);

6. You can match and replace, using part of the incoming string that matched in the output:
  $rv1 = preg_replace('/(.b)ury/','flower',$info);

7. And you can match and replace, using a function run on the input match to work out the replacement string:
  $rv1 = preg_replace_callback('/(North|South|East|West)/',"compass",$info);

Complete example, including the source code of the function compass used in the last example, [here].