Search code examples
phpregexpreg-match

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


I am having trouble I could not fix this error. I am using this upload script to check the mime type.

Warning: preg_match(): Unknown modifier 'p'
Warning: preg_match(): Unknown modifier 'g'
Warning: preg_match(): Unknown modifier '('

if (preg_match('/^image/p?jpeg$/i', $_FILES['upload']['type']) or 

    preg_match('/^image/gif$/i', $_FILES['upload']['type']) or 

    preg_match('/^image/(x-)?png$/i', $_FILES['upload']['type'])) 

{ 

  // Handle the file... 

} 

else 

{ 

  $error = 'Please submit a JPEG, GIF, or PNG image file.'; 

  include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php'; 

  exit(); 

}

Thank you in advance


Solution

  • 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