1
foreach ($expected_lines as $expected_line) {
    if (!preg_match("/$expected_line\s*/", $contents)) {
        $match = false;
        $unmatched = $expected_line;
        break;
    }
}

This is my code which give me error

PHPUNIT_FRAMEWORK_ERROR_WARNING

preg_match(): Unknown modifier 'G'

Let me know where i m gone wrong

Community
  • 1
  • 1
srs
  • 23
  • 6
  • Error is absolutely in your variable $expected_line! So show this up – MrSmile Jun 18 '18 at 05:40
  • You likely forgot to escape a slash in your pattern, e.g. you got something like `/foo/G/` when it has to be `/foo\/G/`. But we need to see the actual pattern. – Gordon Jun 18 '18 at 06:24
  • 1
    When you generate a `regex` using dynamic content you need to use [`preg_quote()`](http://php.net/manual/en/function.preg-quote.php) to properly encode the dynamic content. It escapes any character of its argument that has a special meaning in `regex`. The value of `$expected_line` contains `/G`. Because the `/` is not escaped, `preg_match()` thinks this is where the `regex` ends and the next character (`G`) is a [modifier](http://php.net/manual/en/reference.pcre.pattern.modifiers.php), hence the error message. – axiac Jun 18 '18 at 10:20

1 Answers1

2

It seems that the regular expression passed to preg_match is incorrect after actual value of $expected_line is used in "/$expected_line\s*/".

Everytime you use data you got from users in regular expressions, you need to properly escape it to avoid situations like that - when characters provided by user break the expression. Use preg_quote for that:

$escaped_expected_line = preg_quote($expected_line, '/');
if (!preg_match("/$escaped_expected_line\s*/", $contents)) {
   ...
}

Check here for more info: https://secure.php.net/manual/pl/function.preg-quote.php

jedrzej.kurylo
  • 39,591
  • 9
  • 98
  • 107