2011-09-19 132 views
1

我需要用正則表達式一點幫助,以匹配和替換正則表達式匹配和替換單詞分隔某些字符

<comma|dash|fullstop|questionmark|exclamation mark|space|start-of-string>WORD<comma|dash|fullstop|space|end-of-string> 

我需要找到其

前面有一個特定的詞(不區分大小寫):逗號或破折號或句號或問號或感嘆號或空間或啓動的串

和後跟:逗號或破折號或句號或問號或感嘆號或空間或結束字符串

測試字符串: MATCH我,是請,配我,但dontMATCHme MATCH我當然比賽中和,最後MATCH

我想替換所有比賽用PHP另一個字符串,所以我可能需要使用的preg_replace!或者其他的東西?

回答

1

試試這個

$input = "MATCH me, yes please,MATCH me but dontMATCHme!MATCH me and of course MATCH, and finally MATCH"; 

echo($input."<br/>"); 
$result = preg_replace("/ 
         (?:^    # Match the start of the string 
         |(?<=[-,.?! ])) # OR look if there is one of these chars before 
         match   # The searched word 
         (?=([-,.?! ]|$)) # look that one of those chars or the end of the line is following 
         /imx",   # Case independent, multiline and extended 
         "WORD", $input); 
echo($result); 
0

這是PHP中的一個實現,它將完成您描述的任務。它將用「WORD」替換所有的單詞。

<?php 

$msg = "MATCH me, yes please,MATCH me but dontMATCHme!MATCH me and of course MATCH, and finally MATCH"; 

echo($msg."<br/><br/>"); 
$msg = preg_replace("/(\w)+/", "WORD", $msg); 
echo($msg."<br/>"); 

?> 
+0

是的,這個定義 「詞」 的(字母,數字和下劃線)都確定了我。我怎樣才能用這種方法替換一個特定的詞? – Sharky

+0

我設法解決這個,我想出了這個(警告:我不知道這是多麼有效,我沒有徹底測試它): eregi_replace('([ - \。,\ + \?\( \)\ $ \ [\]; _ =])'。$ oldvalue。'([ - \。,\ + \?\(\)\ $ \ [\]; _ =])',「\\ 1 」。$ NEWVALUE。 「\\ 2」,$字符串); 如果任何人都可以將其轉換爲preg_replace,我將是gratefull ...如果有人可以幫我解決這個問題:http://stackoverflow.com/questions/7479185/transform-ereg-replace-to-preg-替換 (我發表評論,因爲所以不會讓我自我回答5小時) – Sharky

+0

我更新了工作的PHP webapp的例子。試試看看它是否滿足你的需求。另外,如果單詞處於行首或行末,我認爲您的正則表達式不會起作用。 –

0

這不是做的正是你問什麼,但可能滿足您的實際要求更好的(我猜是「與WORD只有MATCH是更換MATCH整個單詞,而不是一個不同的詞的一部分「):

$input = 'MATCH me, yes please,MATCH me but dontMATCHme!MATCH me and of course MATCH, and finally MATCH' 
$result = preg_replace('/\bMATCH\b/i', "WORD", $input) 

\b是詞邊界錨僅米atch在字母數字詞的開始或結尾。

結果:

WORD me, yes please,WORD me but dontMATCHme!WORD me and of course WORD, and finally WORD 
相關問題