Regular Expression modifiers in PHP - summary table
Archive - Originally posted on "The Horse's Mouth" - 2011-11-12 08:13:15 - Graham Ellis
PHP's ereg functions are deprecated, and you should now be moving to the preg functions. See [here]. As you're switching your PHP code from ereg to preg regular expressions, you'll be adding delimiters to the main regular expression and providing the ability to add modifiers onto the end - a series of single letters each of which alters a behaviour throughout the regular expression.
Perl users may be familiar with the following, all of which are also available in PHP's preg functions:
i ignore case m match ^ and $ at embedded new lines as well as very start and end of string s matches anything (by default matches anything except \n) x white spaces and comments (# to line end) are treated as comments e preg_replace only. evaluate OUTPUT string as PHP code and substitute the result
In addition, PHP also supports the following modifiers:
A assume ^ anchor at start D assume $ anchor at end S Study; do more initial analysis for faster matching U default counts to sparse (ungreedy). Extra ? becomes greedy (i.e. invert default) X unknown \letter combination's are to throw an error not be ignored J Allow duplicate names for sub-patterns u treat patterns as UTF-8 rather than ASCII
However, these two perl modifiers are NOT available in PHP:
g global (use count instead on preg_replace, or use preg_match_all rather than preg_match) o once only. An efficiency thing in Perl. No code change needed in PHP
The full technical reference that describes each of these in detail (but currently lacks my summary table!) is [here]. We cover regular expressions in PHP on both our earning to program in PHP and PHP Programming courses. They are covered in more depth on our PHP techniques course - a second level course which helps delegates who already know PHP make the best of the language, and we also offer a complete Regular Expressions day.