Php 用preg_replace()替换不推荐的ereg_replace()无效
下面的PHP程序将替换这些符号!英镑$%^&带空Php 用preg_replace()替换不推荐的ereg_replace()无效,php,deprecated,Php,Deprecated,下面的PHP程序将替换这些符号!英镑$%^&带空 <?php $string = "This is some text and numbers 12345 and symbols !£$%^&"; $new_string = ereg_replace("[^A-Za-z0-9 (),.]", "", $string); echo "Old string is: ".$string."<br />New string is: ".$new_string; ?
<?php
$string = "This is some text and numbers 12345 and symbols !£$%^&";
$new_string = ereg_replace("[^A-Za-z0-9 (),.]", "", $string);
echo "Old string is: ".$string."<br />New string is: ".$new_string;
?>
输出:
旧字符串是:这是一些文本和数字12345和符号!英镑%^&新字符串是:这是一些文本和数字12345和符号 但是,我了解到函数ereg_replace()已经被弃用,我应该使用函数preg_replace()。我是这样做的:
<?php
$string = "This is some text and numbers 12345 and symbols !£$%^&";
$new_string = preg_replace("[^A-Za-z0-9 (),.]", "", $string);
echo "Old string is: ".$string."<br />New string is: ".$new_string;
?>
但是得到了错误的输出:
旧字符串是:这是一些文本和数字12345和符号!£$%^&
新字符串是:这是一些文本和数字12345和符号!英镑%^&
我做错了什么?如何修复它?这也是我遇到的一个奇怪的错误。出于某种原因,空引号使这个函数出错,但我使用
preg_replace($pattern, NULL, $string);
而不是
preg_replace($pattern, "", $string);
您似乎缺少正则表达式周围的标记。试试这个(注意模式周围的斜线)
本页解释POSIX正则表达式(由ereg_替换使用)和PCRE正则表达式(由preg_替换使用)之间的差异:感谢@TheOx。发布后不久,我查看了手册,发现在使用preg_replace()时需要在模式中添加分隔符。因此,使用“/”作为分隔符,模式“[^A-Za-z0-9(),.]”将变成“/[^A-Za-z0-9(),.]/”。呃,您使用的是哪个版本的PHP?“我从来没有见过这种情况。@布劳尔,请看我对上述TheOX的评论。我能够使用“”而不是null,并且它工作正常。重要的是在preg_replace()中使用分隔符。
$string = "This is some text and numbers 12345 and symbols !$%^&";
$new_string = preg_replace("/[^A-Za-z0-9 (),.]/", "", $string);
echo "Old string is: ".$string."<br />New string is: ".$new_string;
$string = "This is some text and numbers 12345 and symbols !$%^&";
$new_string = preg_replace("~[^A-Za-z0-9 (),.]~", "", $string);
echo "Old string is: ".$string."<br />New string is: ".$new_string;