1

Why is preg_match_all not working?

$pattern = '/\{(?:[^{}]|(?R))*\}/';

$result = 161240 characters

       if (preg_match_all($pattern, $result, $matches)) {
            echo 'Success';
        } else {
            echo 'Not working';
        }

This Displays: "Not working"

Amit Verma
  • 40,709
  • 21
  • 93
  • 115
Mark D
  • 13
  • 5

1 Answers1

0

The pattern at play matches balanced curly brackets using regex recursion. The pattern itself looks fine and works as intended.

<?php
$re = '/{(?>[^{}]|(?R))*\}/m';
$str = 'Why is preg_match_all not working?{{{{{
$pattern = \'/\\{(?:[^{}]|(?R))*\\}/\';
$result = 161240 characters
       if (preg_match_all($pattern, $result, $matches)){ {
            echo \'Success\';
        } else {
            echo \'Not working\';
        }
}}}}}}{}{}{}{}{}{}{}{{{{{{}}}}}';

//preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
if (preg_match_all($re, $str, $matches)) {
echo 'Success\n';
} else {
echo 'Not working\n';
}

// Print the entire match result
var_dump($matches);

This also works with larger input (here tested with ~5000 characters). The most likely explanation is: the pattern does not find a valid match.

However, you are running a recursive regex on a very large input string. Many, things could go wrong. The PCRE engine reaches internal limits, your string is not properly encoded, timeouts, etc.

wp78de
  • 18,207
  • 7
  • 43
  • 71