Regular Expressions in PHP

If you already know how to write regular expressions then you should have no trouble in using regular expressions in PHP because regular expressions work basically the same way in PHP as they do in other programming languages. The only difference is how you call the code to run the regular expression.

There areactually several different sets of functions youcan use to do regular expression processing in PHP but the ones that you should be using because they provide the most compatible functionality all start with preg_ followed by the particular function that is to be performed. For example:

preg_match('/^[A-Z \-\']{2,}$/i', $author, $out)

This PHP is equivalent to the following JavaScript in that it finds all of the occurrences within $author that match the regular expression and loads them into an array.

$out = $author.match(/^[A-Z \-\']{2,}$/i)

The PHP version is actually slightly more versatile in that the function itself also returns a number to indicate how many matches were found. Note also how PHP regular expressions need to be enclosed inside a quoted string in order to function rather than the slashes that JavaScript uses. The regular expression itself still needs to be wrapped in a delimiiter such as slash so that any optional modifiers on the end can be identifiied. Unlike JavaScript this need not be slashes and any character at all can be substituted.

The replace version in PHP is also more flexible.

/* PHP */ preg_replace($pattern, $replacement, $string)
/* JavaScript */ $string.replace($pattern,$replacement)

With this one the PHP version can accept either strings or arrays of strings for $pattern and $replacement (in the latter case it can do bulk replaces all in the one call).

The split function in both languages also functionssimilarly except for being set out in different ways.

/* PHP */ $keywords = preg_split("/[\s,]+/", $words)
/* JavaScript */ $keywords = $words.split(/[\s,]+/)

Note that PHP does not have an equivalent to the search() method that JavaScript provides since the extended functionality of preg_match means that it can also be used to perform that processing.

Note also that PHP also allows additional optional parameters into each of these functions that can further define how they work increasing the flexibility in the way you can use them.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow