Php 对文件中的字使用preg_replace无效
这是我的消息来源Php 对文件中的字使用preg_replace无效,php,preg-replace,Php,Preg Replace,这是我的消息来源 $Message = $_GET["message"]; $Username = htmlspecialchars($_GET["username"]); $unix = ($_GET["time"]); include 'mcheck.php'; $file1 = file_get_contents('filter.txt'); $bad_words = explode(PHP_EOL, $file1); $compare = explode('', $Messag
$Message = $_GET["message"];
$Username = htmlspecialchars($_GET["username"]);
$unix = ($_GET["time"]);
include 'mcheck.php';
$file1 = file_get_contents('filter.txt');
$bad_words = explode(PHP_EOL, $file1);
$compare = explode('', $Message);
foreach ($bad_words as $bad_word)
$Message = preg_replace('/\b('.$bad_word.')\b/i', "***", $Message);
echo $Message;
说这个坏词是go
和$Message=我喜欢上学
我想让它呼应我喜欢去学校
但是我得到的是
***I***Like***To******to***school***
我不知道问题出在哪里根据输出,您的数组中可能有一个空元素。所以它最终匹配了一个单词边界(
\b
)
要确认此操作,请添加以下内容以调试代码:
$bad_words = explode(PHP_EOL, $file1);
print_r($bad_words);
顺便说一句,重复每一个坏话都是浪费。我建议在解决上述问题后,使用一个带有修改的正则表达式
例如:
\b(one|two|three)\b
我认为您需要从分解结果数组中删除空字段为什么不直接使用
str\u replace
范例
$badWords = array("go","school");
$message = " I like to go to school" ;
$newMessage = str_replace($badWords, "***", $message);
echo $newMessage ;
输出
I like to *** to ***
为此,您应该使用
strtr
您可以使用key=>replace传递数组,这将比preg\u replace更有效
除此之外,dic肯定是坏字眼。您的文件最有可能以换行符结尾(这是一件好事:所有*nix系统上的文本文件都应该是这样),这意味着
explode(PHP_EOL,$file1)
的最后一个元素是空的(它是最后一个换行符和文件结尾之间的所有内容,没有任何内容)。我建议写:
$file1 = trim(file_get_contents('filter.txt'));
用于消除最后一条换行符。那么它与单词boundry匹配了吗?我不想让它拾取已经进入其中的单词,比如乐高。单词boundary很好,问题在于它的捕获是空的。好吧,这是你的,它工作得很好,所以我认为你的
$bad\u单词
不是你所认为的。)是的,它将取代“go”、“Goe”和“arsegole”<代码>preg_replace的使用是有原因的。正是@raina77ow。运行:$message='他去上学'代码>。孩子们,不要在家里这样做。:)如前所述,strtr
将匹配go、go、go等。因此,如果您需要替换不一定是坏格的坏字,则使用正则表达式;)但是同意了regex。