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

被PHP的正则打败了。。。

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-23 14:15:11
Original
1074 people have browsed it

我简单的匹配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/>";
Copy after login
Copy after login


回复讨论(解决方案)

可以呀

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


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

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

$a = "/(\d)(\d)\2\1/";$b = '/(\d)(\d)\2\1/';var_dump($a == $b);var_dump($a, $b);
Copy after login
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);
Copy after login
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/>";
Copy after login
Copy after login

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

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


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

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