2015-04-18 47 views
-3

我需要從句子中替換匹配單詞。我正在使用下面的內容,但區分大小寫。我需要不區分大小寫。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

+0

它看起來那麼像你想替換整個單詞(即串中的空間「」爆炸)只,而不是一個一個字內的子集,這是正確的? – dbinns66

+0

其實我需要突出顯示文字 –

+0

好的,問題是,無論你需要做什麼,只有整個「單詞」?因爲在你的例子中你想高亮「4」,如果你想突出顯示它在任何地方的文字,@ nu11p01n73R的答案是例外,如果只有「單詞」,那麼需要稍微修改版本... – dbinns66

回答

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. 
+0

謝謝兄弟...你救了我很多作品.... :) –

+0

@TapasPal歡迎兄弟:)如果你覺得它有用,請接受答案;) – nu11p01n73R

+0

你能幫我解答我更新的問題嗎? –

2

添加4/5你不能使用字邊界(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 __) 
+0

對不起,如果我在'$ findStringArray'上添加'4/5',它仍然停止工作。 –

+0

@TapasPal:'4/5'需要的結果是什麼? – Toto

+0

輸出應該是'她__是__年__和11__。 (肩一個__)' –