php-src icon indicating copy to clipboard operation
php-src copied to clipboard

regular expressions don't work in 8.1.13 and 8.1.14

Open awn-wgg opened this issue 3 years ago • 3 comments

Description

The following code:

$text = 'src="index.php?act=captcha&{$random}" width="145"'; preg_match_all("/{\s*$([a-z\d]+)\s*}/", $text, $matches); print_r($matches);

Resulted in this output:

Array ( [0] => Array ( ) [1] => Array ( ) )

But I expected this output instead:

must be found '$random' and 'random'

PHP Version

PHP 8.1.14 and PHP 8.1.13

Operating System

windows7

awn-wgg avatar Jan 08 '23 18:01 awn-wgg

There are two mistakes in your code:

  1. $ means "end of line", it should be \$
  2. by using double quotes instead of single quotes, you risk variable substitution

The following code works for me:

<?php
$text = 'src="index.php?act=captcha&{$random}" width="145"';
preg_match_all('/{\s*\$([a-z\d]+)\s*}/', $text, $matches);
print_r($matches);
?>

ndossche avatar Jan 08 '23 18:01 ndossche

@awn-wgg you can test your snippet here https://3v4l.org/lgihC and see, that is has the same behaviour also in 8.0.* and 8.2.* (and 7.4.*), which is a good indicator that the problem is probably in the snippet (as @nielsdos explained) and not php bug.

pospjan avatar Jan 08 '23 21:01 pospjan

I have a backslash before $ in my program. I don't understand how I could insert a row without it. The line looks like this -

	preg_match_all("/\{\s*\$([a-z\d]+)\s*\}/", $text, $matches);

But the regex doesn't work in all versions of php. In this I was convinced in https://3v4l.org/lgihC. Replacing double quotes with single quotes helped. I knew it but didn't see it. Thanks for the hints.

awn-wgg avatar Jan 09 '23 12:01 awn-wgg