我需要從句子中替換匹配單詞。我正在使用下面的內容,但區分大小寫。我需要不區分大小寫。Php大小寫不敏感的單詞從句子替換
$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)
而且也是它停止工作,如果我在$findStringArray
它看起來那麼像你想替換整個單詞(即串中的空間「」爆炸)只,而不是一個一個字內的子集,這是正確的? – dbinns66
其實我需要突出顯示文字 –
好的,問題是,無論你需要做什麼,只有整個「單詞」?因爲在你的例子中你想高亮「4」,如果你想突出顯示它在任何地方的文字,@ nu11p01n73R的答案是例外,如果只有「單詞」,那麼需要稍微修改版本... – dbinns66