Home >Backend Development >PHP Tutorial >被PHP的正则打败了。。。

被PHP的正则打败了。。。

WBOY
WBOYOriginal
2016-06-23 14:15:111052browse

我简单的匹配abba 这样的4个连续的数字,里面使用了子表达式和反向引用,结果没有捕获到,真不知道为什么,我哪里写错了?

<?phpheader("Content-type:text/html;charset=utf-8");$str="fdsafsdafsgfdag1223fa1551sdfassd3265";$mypreg="/(\d)(\d)\2\1/";//匹配abba式的数字,即上面的1551$mycon="这是数字";$str=preg_replace($mypreg,$mycon,$str);echo $str."<br/>";


回复讨论(解决方案)

可以呀

$str="fdsafsdafsgfdag1223fa1551sdfassd3265";$mycon="这是数字";$str=preg_replace('/(\d)(\d)\2\1/',$mycon,$str);echo $str."<br/>";
fdsafsdafsgfdag1223fa这是数字sdfassd3265


但直接复制你的代码就不行
估计是你的编辑器有问题

嗯,是双引号的问题
在双引号中字符的转义符生效了

$a = "/(\d)(\d)\2\1/";$b = '/(\d)(\d)\2\1/';var_dump($a == $b);var_dump($a, $b);
bool(false) string(12) "/(\d)(\d)/" string(14) "/(\d)(\d)\2\1/" 

要这样
$a = "/(\d)(\d)\\2\\1/";$b = '/(\d)(\d)\2\1/';var_dump($a == $b);var_dump($a, $b);
bool(true) string(14) "/(\d)(\d)\2\1/" string(14) "/(\d)(\d)\2\1/" 

所以你会看到一些正则表达式中会有一连串的 \
\\\、\\\\....
总之是不对就加一个

我简单的匹配abba 这样的4个连续的数字,里面使用了子表达式和反向引用,结果没有捕获到,真不知道为什么,我哪里写错了?

<?phpheader("Content-type:text/html;charset=utf-8");$str="fdsafsdafsgfdag1223fa1551sdfassd3265";$mypreg="/(\d)(\d)\2\1/";//匹配abba式的数字,即上面的1551$mycon="这是数字";$str=preg_replace($mypreg,$mycon,$str);echo $str."<br/>";

PHP中使用正则建议使用单引号,即:

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


因为PHP的\在双引号中会起转义作用

Statement:
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