Skip to content

PHP 7.3: detect regexes affected by the change-over to PCRE2 #965

@jrfnl

Description

@jrfnl

Originally requested by @jkbzh in squizlabs/PHP_CodeSniffer#2741

Conversation copied in from the original ticket.


@jkbzh

Hi,

PHP 7.3 migrated from PCRE to PCRE2 . PCRE2 is stricter and requires escaping of hiphens in regular expressions. This is not detected by PHPCS. If this makes sense to you, could it be possible to add a test for hiphens and other characters that need to be escaped so that the following sample would raise a REGEXP warning when running phpcs?

<?php

$tag="j";

if (preg_match("/^[\w-:]+$/", $tag)) {
    print "match";
} else {
    print "no match";
}

PHP 7.3 on the above code gives:
Warning: preg_match(): Compilation failed: invalid range in character class at offset 4 in /usr/local/src/test.php3 on line 5

Thanks!


@jrfnl

@jkbzh That would be a sniff I'd happily add to PHPCompatibility, though won't be easy to sniff for unless the regex is a string literal within a regex function call. If it's a variable/constant etc, we won't have access to the runtime value of the variable, so we're out of luck.

To write it, I'd need quite some code samples though, so any additional code samples you can think of would be helpful.


@austinpray

Here's some code samples!

broken

<?php

$path = '/carrot/v1/site/43050/analytics';
$route = '/carrot/v2/sites/(?P<blog_id>\d+)/migrations/(?P<migration>[\w-_]+)';

var_dump(preg_match( '@^' . $route . '$@i', $path, $matches ));
var_dump($matches);

fixed

<?php

$path = '/carrot/v1/site/43050/analytics';
$route = '/carrot/v2/sites/(?P<blog_id>\d+)/migrations/(?P<migration>[\w\-_]+)';

var_dump(preg_match( '@^' . $route . '$@i', $path, $matches ));
var_dump($matches);

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions