The importance of regular expressions - pt 2

Tuesday, 1 July 2008

Following on from my previous entry on regular expressions, I'd like to go over some of the useful functions that are built in to php for dealing with regular expression.

The two most common functions that I think you will come across are preg_match and preg_replace.

We'll start by looking at preg_match. preg_match goes through the given subject to see if it matches the given pattern, which is the simplest form of this function. The function then simply returns 1 if if finds a match or 0 otherwise.

The next important thing to look at is the $matches variable. With a basic call we simply get the match at the first index of the matches array:
preg_match("/ello/", "hello", $matches);


will give:
[0] => ello

As stated on "If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on. "

So what we will see in $matches[1] etc. is the text that matched parenthesized subpatterns. Let's look at a simple example:
$subject = "hello";

preg_match("/he(l)+o/", $subject, $matches);


[0] => hello
[1] => l
You can see clearly that in $matches[0] we have the full text match and in $matches[1] we have the l that matched in the parenthesis. Note that as we are using preg_match it will only show the first match and not subsequent matches although the second 'l' also matches. This is covered in the function preg_match_all.
blog comments powered by Disqus