2012-01-23 75 views
1

我有preg_match_all和str_replace函數有點問題PHP preg_match_all和str_replace函數

<? 
    $source = 'hello @user_name, hello @user_name2, hello @user_name3'; 
    preg_match_all("/@[\w\d_]*/s", $source, $search); 
    foreach($search[0] as $result) { 
     $source = str_replace($result, "<b>okay</b>", $source); 
    } 

    echo $source; 
?> 

結果是(錯誤):

hello <b>okay</b>, hello <b>okay</b>2, hello <b>okay</b>3 

正確的結果應該是這樣的:

hello <b>okay</b>, hello <b>okay</b>, hello <b>okay</b> 

任何人都可以幫忙嗎? 謝謝!

回答

1

這是因爲第一場比賽@user_name也會匹配@user_name2@user_name3(至少@user_name部分)。你寫它的方式,它是按照它應該的方式工作的。你可能想看看preg_replace()。爲了測試正則表達式模式,我總是使用My Regex Tester(這實際上不是我的,這只是它的名字)。下面是該網站的輸出,完整的代碼生成:

Raw Match Pattern: 
@[\w\d_]* 

Raw Replace Pattern: 
okay 

PHP Code Example: 
<?php 
$sourcestring="hello @user_name, hello @user_name2, hello @user_name3"; 
echo preg_replace('/@[\w\d_]*/s','<b>okay</b>',$sourcestring); 
?> 

$sourcestring after replacement: 
hello <b>okay</b>, hello <b>okay</b>, hello <b>okay</b> 
+0

嗨Crontab,感謝您的建議..我嘗試使用'$ source = preg_replace('/'.$ result。'/',''。$ result。' (',$ source);'但結果是一樣的。:( –

+0

我的意思是讓你自己使用'preg_replace()'而不是使用'preg_match_all()'和'str_replace()'串聯。 – Crontab

+0

hmm,如果我不使用'preg_match_all',我不知道用什麼字符串跟@ @必須替換爲..?它怎麼樣? –

0

你的問題是不是與preg_match_all或的preg_replace。問題在於str_replace。 創建搜索陣列後,第一個標記包含的值爲「user_name」,並且str_replace函數將字符串中的所有三次出現都替換掉。所以1和2的值仍然是字符串。

如果你改變你的源作爲

$source = 'hello @user_name1, hello @user_name2, hello @user_name3'; 

它將很好地工作。否則你需要以相反的順序迭代數組