Home > Backend Development > PHP Tutorial > php正则表达式和js正则表达式居然不一样?

php正则表达式和js正则表达式居然不一样?

WBOY
Release: 2016-06-23 14:15:07
Original
823 people have browsed it

我使用js的正则没有问题,然后同样的写成php正则,居然匹配不到,两者的正则不一样?


如,我匹配4个连续且全部相同的数字,同样的串,同样的规则,js可以匹配成功,php匹配不到,

js:

var str="fasdgasgdfgfduuuuuu1221uuuuufasdfsdfsdaf4444";var myreg=/(\d)\1{3}/gi;var mycon="数字";var str=str.replace(myreg,mycon);document.write(str);
Copy after login
Copy after login


php:
<?phpheader("Content-type:text/html;charset=utf-8");$str="fasdgasgdfgfduuuuuu1221uuuuufasdfsdfsdaf4444";$mypreg="/(\d)\1{3}/i";$mycon="这是数字";echo $str."<br/>";		$str=preg_replace($mypreg,$mycon,$str);echo $str."<br/>";
Copy after login
Copy after login


js成功将4444匹配,php没有获取到。惊!!!!!!!!!!


回复讨论(解决方案)

$str="fasdgasgdfgfduuuuuu1221uuuuufasdfsdfsdaf4444";
$mypreg="/(\d{4})/i";
$mycon="this is number";
$str=preg_replace($mypreg,$mycon,$str);
echo $str."
";
//fasdgasgdfgfduuuuuuthis is numberuuuuufasdfsdfsdafthis is number

我觉得主要问题是php无法使用反向捕获的原因。

或者php的反向捕获不是\1 \2这样的

双引号中转义生效了!

$a = "/(\d)\1{3}/i";$b = '/(\d)\1{3}/i';var_dump($a == $b);var_dump($a, $b);
Copy after login
bool(false) string(11) "/(\d){3}/i" string(12) "/(\d)\1{3}/i"

我使用js的正则没有问题,然后同样的写成php正则,居然匹配不到,两者的正则不一样?


如,我匹配4个连续且全部相同的数字,同样的串,同样的规则,js可以匹配成功,php匹配不到,

js:

var str="fasdgasgdfgfduuuuuu1221uuuuufasdfsdfsdaf4444";var myreg=/(\d)\1{3}/gi;var mycon="数字";var str=str.replace(myreg,mycon);document.write(str);
Copy after login
Copy after login


php:
<?phpheader("Content-type:text/html;charset=utf-8");$str="fasdgasgdfgfduuuuuu1221uuuuufasdfsdfsdaf4444";$mypreg="/(\d)\1{3}/i";$mycon="这是数字";echo $str."<br/>";		$str=preg_replace($mypreg,$mycon,$str);echo $str."<br/>";
Copy after login
Copy after login


js成功将4444匹配,php没有获取到。惊!!!!!!!!!!

正则没有错,主要是PHP你使用了双引号,导致\这个符号转移生效了

所以只要使用单引号号就可以了,即:

$str="fasdgasgdfgfduuuuuu1221uuuuufasdfsdfsdaf4444";$mypreg='/(\d)\1{3}/i';$mycon="这是数字";echo $str."<br/>";        $str=preg_replace($mypreg,$mycon,$str);echo $str."<br/>";
Copy after login

建议无论是不是双引号和单引号之中,如果想用单个 \字符,最好都是用 \\来表示,这样是不会出现歧义的,尽管单引号仅检测 \'转义

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template