在PHP中,我有一个单词数组,我想搜索并替换字符串中不区分大小写的完全匹配。例如:
$pattern = array("base", "all");
$str = "first base baseball for all";
$str = str_ireplace($pattern, "FOUND", $str);
echo $str;
输出:找到FOUND的第一个FOUND FOUNDbFOUND 预计:FOUND的第一个FOUND棒球
我不希望'棒球'被替换,因为我只想要替换整个单词。有没有办法实现这个目标?
答案 0 :(得分:11)
使用preg_replace()
代替str_ireplace()
,因为您可以在正则表达式中定义单词边界。
$str = "first base baseball for all";
$pattern = '/\b(base|all)\b/i';
$str = preg_replace($pattern, "FOUND", $str);
echo $str;
// first FOUND baseball for FOUND
如果从数组开始,可以执行此操作以从数组中构建正则表达式:
$words = array('base','all');
// implode() words into a pipe-delimited string
$pattern = '/\b(' . implode("|", $words) . ')\b/i';
$str = preg_replace($pattern, "FOUND", $str);