2012-11-01 36 views
0

這裏是我的問題:腓更換確切的詞

使用preg_replace('@\b(word)\[email protected]','****',$text);

凡在文本我有word\word and word,在preg_replace上述取代了word\wordword所以我得到的字符串是***\word and ***

我希望我的字符串看起來像:word\word and ***

這可能嗎?我究竟做錯了什麼???

以後編輯

我有一個網址,一個數組,我的foreach數組和的preg_replace其中URL是找到文本,但它不工作。

舉例來說,我有http://www.link.comhttp://www.link.com/something

如果我有http://www.link.com它也取代http://www.link.com/something

+0

還有什麼可以繼續嗎?這個詞總是在字符串的末尾嗎?以前的那些總是接近反斜槓......? – deceze

+2

那麼你可能需要'\ s'而不是'\ b',因爲反斜槓也是一個字邊界:)當然,'\ s'在字符串的開始/結束處不匹配。 –

+0

也許爆炸$文本的空間到一個數組,然後foreach你的方式通過,如果這個詞= word \ word離開它否則改變它***可能? – Chris

回答

2

您正在有效地指定您不希望某些字符計爲字邊界。因此,你需要指定「邊界」自己,是這樣的:

preg_replace('@(^|[^\w\\])(word)([^\w\\]|$)@','**',$text); 

這樣做是由行邊界或者非單詞字符包圍,除了背面的搜索削減\。因此它將匹配word,而不是word \而不是'\ word。如果您需要從匹配中排除其他字符,只需將它們添加到括號內即可。

0

你可以使用str_replace("word\word", "word\word and"),我真的不明白爲什麼你需要在上面給出的情況下使用preg_replace。

+0

他不想取代'字\措辭' –

+0

這不是什麼OP是要求他想要取代所有比賽,除了某些單詞邊界。 –

+0

是的,在我添加了我的答案後,他編輯了幾個問題。不是很奇怪,我的回答沒有幫助,那是嗎? – svenbravo7

0

這是一個簡單的解決方案,不使用正則表達式。它只會替換單詞中出現單詞的單個單詞。

<?php 
$text = "word\word word cat dog"; 
$new_text = ""; 
$words = explode(" ",$text); // split the string into seperate 'words' 

$inc = 0; // loop counter 
foreach($words as $word){ 

    if($word == "word"){ // if the current word in the array of words matches the criteria, replace it 
     $words[$inc] = "***"; 
    } 
    $new_text.= $words[$inc]." "; 
    $inC++; 
} 

echo $new_text; // gives 'word\word *** cat dog' 
?>