Search code examples
phpregexpreg-match-all

PHP 7 regex not working the same way as in 5


So I have to use php 7 and I have the following regex which works just fine in 5.5 and 5.6.

([\\'\\\"].*[\\'\\\"])([\\s]*[\\s]*=>[\\s]*[\\s])(\\[([^\\[\\]]|(?R))*[\\s]*[\\s]\\])/m

when I run this in any version of 5 with preg_match_all I get the correct result. Basically I am trying to match an array in a text file of the form

'key' => [
   'val1 => 'sdsd',
   'val2' => '3e3',  
]

The above expression selects this array. In PHP 7 (7.0.8 and 7.0.9) returns no matches what so ever.

Anyone has any ideas as to why and better yet how do we port expressions to 7?

Edit :

The code used

can be found in this gist

What is weird, is that it does work on some versions of php 7. For example, my VM is running

PHP 7.0.9-1+deb.sury.org~trusty+1 (cli) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
with Zend OPcache v7.0.9-1+deb.sury.org~trusty+1, Copyright (c) 1999-2016,        by Zend Technologies

and it works fine, the production server on the other hand, runs

PHP 7.0.9 (cli) (built: Jul 22 2016 11:36:32) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
with Zend OPcache v7.0.9, Copyright (c) 1999-2016, by Zend Technologies

and it doesn't work at all. $matches is always empty no matter what. Same thing on another ubuntu desktop i'm using. It also doesn't work on windows using

PHP 7.0.9 (cli) (built: Jul 20 2016 10:47:41) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies

It works on all machines using various 5.x versions


Solution

  • I've got it to work with this regex (matches are the same than in your requirement):

    $matchArray = '~([\'"][^\'"]*[\'"])(\s*=>\s+)(\[(?:[^\[\]])*\s+\])~m';
    

    instead of yours:

    $matchArray = '~([\'"].*[\'"])([\s]*[\s]*=>[\s]*[\s])(\[([^\[\]]|(?R))*[\s]*[\s]\])~m';
    

    See buggy version and working version.

    I would say that it's due to some timeout changes but I can't find any reverent information about that.