"Unknown Modifier 'G' In..." When Using Preg_Match in PHP

Unknown modifier 'g' PHP regex error

Switching to preg_match_all was correct, now all you need to do is remove the 'g' from your regex:

$regexp = '/(productimages\/)(\w*)(\/v\/)(\w*)(.jpg)/';

preg_match(): Unknown modifier ')'

The main issue is that you failed to properly escape the backslash. You need four backslashes to match a literal backslash in a PHP string literal. Also, if your pattern contains so many backslashes you should think of using a different regex delimiter.

I suggest

 preg_match("~(/.*?/)((?:[^/]|\\\\/)+?)(?:(?<!\\\\)\s|$)~", $line, $matches);

The tilde as a regex delimiter will make the pattern cleaner since there is no longer need to escape backslashes.

When does preg_match(): Unknown modifier error occur?

If the first name or last name contains a /, your regex will look something like:

/john/doe$/

To preg_match, this looks like the regex is /john/, with the trailing doe$/ being the modifiers. Those are of course invalid modifiers. You need to escape the regex delimiters (/) inside the regex itself using preg_quote.

preg_match error Unknown modifier '('

Escape / in the regular expression.

"/^([1-9]|0[1-9]|[1,2][0-9]|3[0,1])\/([1-9]|1[0,1,2])\/\d{4} ([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}(:([0-5][0-9])){1,2}$/"
# ^ ^

Otherwise, / is recognised as end of the regular expression.

Or use different delimiters:

"#^([1-9]|0[1-9]|[1,2][0-9]|3[0,1])/([1-9]|1[0,1,2])/\d{4} ([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}(:([0-5][0-9])){1,2}$#"

what causes Warning: preg_match(): Unknown modifier 'p'

Everything after second / (closing delimiter) is considered flags. Use another delimiter such as ~

~^image/p?jpeg$~i

Or to match the delimiter literal inside the pattern escape it using the backslash:

/^image\/p?jpeg$/i

Most comfortable to pick a delimiter, that you don't need inside the pattern > no worry for escaping. Frequently used delimiters are /,~,#,@ or even bracket style delimiters such as ( pattern ).


side note


You could combine all three preg_match to a single one using alternation:

if(preg_match('~^image/(?:gif|p?jpeg|(?:x-)?png)$~i', $_FILES['upload']['type'])) { ... }

(?: starts a non-capture group. Good for testing: regex101.com



Related Topics



Leave a reply



Submit