Replacing deprecated ereg_replace() with preg_replace() did not work

谁都会走 提交于 2020-01-16 04:05:06

问题


The following PHP program replaces the symbols !£$%^& with nulls

 <?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;

 ?>

Output:

Old string is: This is some text and numbers 12345 and symbols !£$%^&
New string is: This is some text and numbers 12345 and symbols

But, I have learned that the function ereg_replace() has been deprecated and that I should use the function preg_replace() instead. I made the substitution like so:

 <?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;

 ?>

but got the wrong output:

Old string is: This is some text and numbers 12345 and symbols !£$%^& New string is: This is some text and numbers 12345 and symbols !£$%^&

What did I do wrong? How do I fix it?


回答1:


You seem to be missing markers around the regular expression. Try this instead (note the slashes around the pattern).

$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;

You can use any character for the markers as long as the same one is found on both sides. Very useful if your pattern is matching / characters. So this is also valid:

$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;



回答2:


This is a weird bug that I have experienced as well. for some reason the empty quotes screw up this function but I got it to work by using

preg_replace($pattern, NULL, $string);

instead of

preg_replace($pattern, "", $string);


来源:https://stackoverflow.com/questions/9741740/replacing-deprecated-ereg-replace-with-preg-replace-did-not-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!