Related: PHP CodeSniffer: T423831: add rule to warn or require 2nd parameter when using PHP's preg_quote() function
What
- mass refactor code that both 1) uses PHP's preg_quote() function (preg_quote(string $str, ?string $delimiter = null): string) without a second parameter and 2) has a delimiter that is not automatically escaped. example: /.
- to check: CodeSearch (26 files)
Why
- prevent bugs. omitting the second parameter of the preg_quote() sometimes causes the regex function to not match anything due to incorrect delimiter escaping, and emits a PHP warning. this is because PCRE reads /Test/String/ as a syntax error. it should instead be /Test\/String/. preg_quote() will escape that middle slash if the 2nd parameter is provided.
<?php // The bug $haystack = 'Hi, this contains a Test/String.'; $subpattern = 'Test/String'; $escaped = preg_quote( $subpattern ); $regEx = '/' . $escaped . '/'; // generates PHP warning, then gives no matches preg_match_all( $regEx, $haystack, $matches ); echo $matches[0][0] ?? ''; // The fix: add '/' as the second parameter of preg_quote() $haystack = 'Hi, this contains a Test/String.'; $subpattern = 'Test/String'; $escaped = preg_quote( $subpattern, '/' ); $regEx = '/' . $escaped . '/'; preg_match_all( $regEx, $haystack, $matches ); echo $matches[0][0] ?? '';
Warning: preg_match_all(): Unknown modifier 't' in /home/user/scripts/code.php on line 9 Test/String
- PHP sandbox: https://onlinephp.io/c/db985
- List of delimiters that don't need to be refactored because they're automatically escaped (but it wouldn't hurt to add them): . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - #
- Partial list of delimiters that definitely need to be refactored to avoid bugs: /