PHP正则替换函数preg_replace()报错:Notice Use of undefined constant的解决方法分析

2017-04-04 10:52:37  PHP正则替换pregreplace

本文实例讲述了PHP正则替换函数preg_replace()报错:Notice Use of undefined constant的解决方法。分享给大家供大家参考,具体如下:

环境错误级别:error_reporting =E_ALL

某天我在研究一下php下的正则替换函数perg_replace(),

示例:

代码:

$subject="2222<b>a</b>2222fff222222222A22222"; $pattern = "/(a)/e"; $replacement= "md5($1)";//$1,取匹配到的内存变量的值(\1也可以,只不过要注意双引号内的转义) echo preg_replace($pattern,$replacement, $subject);

结果:

虽然结果是对的,但是报了如下的错误:

Notice: Use of undefined constant a - assumed 'a' in D:\xampp\htdocs\studyRoom egular\index.php(18) : regexp code on line 1

造成这原因的是在$replacement= "md5($1)";中的md5()方法,在参数传递的时候,参数没有加单引号或者双引号,系统就认为是个常量,所以就出现了这样的问题。改成如下 即可:

$replacement= "md5('$1')";(或:$replacement= "md5('\\1')";)

注:在取匹配到的内存变量的值的时候可以用"$1"或者"\1"这样的形式.

PHP正则替换函数preg_replace()报错:Notice Use of undefined constant的解决方法分析》阅读地址:http://www.haoshilao.net/15140/

最新图文教程: