我需要从句子中替换匹配的单词。我正在使用下面但它区分大小写。我需要不区分大小写。
$originalString = 'This is test.';
$findString = "is";
$replaceWith = "__";
$replacedString = (str_ireplace($findString, $replaceWith, $originalString));
// output : Th__ __ test.
然后我试过
$replacedString = preg_replace('/\b('.preg_quote($findString).')\b/', $replaceWith, $originalString);
// output : This __ test.
它按预期正常工作,但如果我使用$findString = "Is"
或"iS"
或"IS"
,那么它无效。
任何人都可以告诉我什么是正则表达式。获得不区分大小写的替换或任何其他方式来实现期望的结果。
已更新
根据@nu11p01n73R
回答,我已在下方进行了更改,但在下面的示例中,它会下降。
$originalString = 'Her (III.1) was the age of 2 years and 11 months. (shoulder a 4/5)';
$findStringArray = array("age", "(III.1)", "2", "months", "4");
foreach($findStringArray as $key => $value) {
$originalString = preg_replace('/\b('.preg_quote($value).')\b/i', "__", $originalString);
}
//Output : Her (III.1) was the __ of __ years and 11 __. (shoulder a __/5)
//Output should be : Her __ was the __ of __ years and 11 __. (shoulder a 4/5)
如果我在4/5
上添加$findStringArray
答案 0 :(得分:4)
您需要做的就是在正则表达式的末尾添加ignore case modifier i
$originalString = 'This Is test.';
$findString = "is";
$replaceWith = "__";
$replacedString = preg_replace('/\b('.preg_quote($findString).')\b/i', $replaceWith, $originalString);
// output : This __ test.
答案 1 :(得分:2)
您不能在(III.1)
或4/5
上使用字边界,请尝试使用:
$originalString = 'Her (III.1) was the age of 2 years and 11 months. (shoulder a 4/5)';
$findStringArray = array("age", "(III.1)", "2", "months", "4/5");
foreach($findStringArray as $key => $value) {
$originalString = preg_replace('~(?<=^|[. (])'.preg_quote($value).'(?=[. )]|$)~i', "__", $originalString);
// __^ __^ __^ __^
}
echo $originalString,"\n";
修改:我已将分隔符从/
更改为~
,并在外观中添加了括号。
<强>输出:强>
Her __ was the __ of __ years and 11 __. (shoulder a __)