替换不推荐使用的ereg

替换不推荐使用的ereg

本文介绍了用preg_replace()替换不推荐使用的ereg_replace()无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下PHP程序替换符号!£$%^&用空值

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;

 ?>

输出:

旧字符串为:这是一些文本和数字12345和符号!£$%^&

新字符串是:这是一些文本和数字12345和符号

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

但是,我了解到不建议使用ereg_replace()函数,而应改用preg_replace()函数。我做了这样的替换:

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;

 ?>

但输出错误:

旧字符串是:这是一些文本,数字12345和符号!£$%^&
新字符串是:这是一些文本和数字12345和符号!£$%^&

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?

推荐答案

您似乎在正则表达式周围缺少标记。请改用此方法(注意图案周围的斜线)。

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;

这篇关于用preg_replace()替换不推荐使用的ereg_replace()无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 21:43