【发布时间】:2016-09-15 22:45:38
【问题描述】:
我有这个 PHP 函数可以用一些单词替换列表文件中的文本中的单词
我的功能
function replace_text_wps($text){
$dir = plugin_dir_path( __FILE__ );
$file= $dir."bad2.list";
$badlist = file($file, FILE_IGNORE_NEW_LINES);
$replace = '[censored]';
$text = str_replace($badlist, $replace, $text);
return $text;
}
例如,我的 bad2.list 中有单词 ABC
当我输入文本 ABC 时,我的函数将 ABC 更改为 [censored] ,但如果我输入单词 DFGABC 将其更改为 DFG[censored]
如何仅替换我文件中的匹配词? 我是 PHP 新手?对不起菜鸟问题
更新:
这是工作版
function replace_text_wps($text){
$dir = plugin_dir_path( __FILE__ );
$file= $dir."bad2.list";
$badlist = file($file, FILE_IGNORE_NEW_LINES);
$replacement = "[CENSORED]";
$badlist = array_map(function($v) { return "\b". $v ."\b"; }, $badlist);
foreach($badlist as $f) {
$text = preg_replace("/".$f."/u", $replacement, $text);
return $text;
}
【问题讨论】:
-
切换
$badlist和$text -
我会建议探索全能和雷鸣般的power of Regex。
-
使用带有
preg_replace()repl.it/D95x/1的单词边界 -
高清,谢谢!您的解决方案 repl.it/D95x/1 对我有用!
标签: php replace str-replace