Solution to: ‘Warning: preg_match() [function.preg-match]: Unknown modifier ‘/’ in …. on line …’

12 July, 2008 (22:51) | PHP-MySQL | By: Rohan Shenoy

Regular expressions by themselves are difficult for many to implement. An error that many of the regex newbies will encounter is:

Warning: preg_match() [function.preg-match]: Unknown modifier ‘/’ in ….. on line …

Solution

This error occurs whenever the pattern you are looking for contains a literal forward-slash. You should escape every literal forward-slash with a backslash.

For those of you interested in knowing more

The syntax for preg_match() is

int preg_match  ( string $pattern  , string $subject  [, array &$matches  [, int $flags  [, int $offset  ]]] )

Example of a pattern to search for alphabetic substrings in a string would be:

$pattern="/[a-z]+/";

In the above, pattern example, the two forward slashes you see are the delimiters. The PHP parser is programmed to understand that anything in-between those two delimiters is the actual pattern we are looking for. However, the pattern we just used above will look only for lowercase alphabets. If we want PHP to look for even upper case or mixed case substrings, we need to inform the PHP parser accordingly.

All such additional instructions are provided to the PHP parser using entities which are called as ‘modifiers’. These modifiers are placed at the end of the pattern, after the delimiting forward-slash. Look below to see how we place the modifier named ‘i’ to instruct PHP parser to do a case-insensitive pattern matching

$pattern="/[a-z]+/i";

Any character appearing after the end delimiting forward slash is ‘assumed’ by the PHP parser as a delimited. A number of delimiters are defined by PHP. A full list of modifiers can be found here.

If you forget to escape a literal forward-slash in your pattern parameter, PHP assumes that the pattern has been ended by the delimiter and characters after that forward-slash are ‘modifiers’. When the parser finds that the modifiers are not defined by PHP, its outputs the error saying ‘Unknown modifier’.

Write a comment