2011-01-08 50 views
0

我已經完成了我的谷歌研究。我嘗試過preg_match,strsub_replace,幾乎所有的東西。從角色中擷取單詞?

老實說,我似乎無法弄清楚如何抓住連接到角色的單詞。

我在我的網站上有一個狀態系統。我試圖弄清楚如果在其中包含字符'@',如何用其他字詞替換一個字詞。就像在twitter上,當你說'@person'時。

任何幫助,非常感謝。

回答

1

只是打印匹配:

preg_match_all("/@([0-9a-z]+)/i",$input,$matches); 
print_r($matches[1]); 

來替換它們:

$input = preg_replace('/@([0-9a-z]+)/i','-->\1<--',$input); 

-->text<--取代@text,作爲一個例子。

+1

有趣。它顯示了人們用'@'寫的所有名字。但是,我需要替換在狀態中找到的所有名稱。我將如何獲取結果的substr(帶有2個參數)? – Seth 2011-01-08 02:53:26

+0

你是什麼意思?請提供樣本輸入和相關輸出。 – mvds 2011-01-08 02:57:41

+1

等一下。你提供的腳本工作。我只需要將文本替換爲,例如: ..如何使用您使用的方法實現這一點? – Seth 2011-01-08 03:00:02

-1

我推薦RegexPal幫助你找出表情。解釋你的問題,你想找到一個以「@」開頭的元素,後跟字符......

<?php 

$isMatches =preg_match_all("/^@.+$/", $stringToSearch, $matches); 

?> 

匹配字符串中的所有模板。

0

所有的答案都好,如果你嘗試匹配,如果你試圖在這裏取而代之的是我怎麼會做到這一點:

$string = "some text @person some other text 
some @pers 
@pess text"; 
var_dump(preg_replace('/@.*\s/i', '#replacement#', $string)); 

其中「#替換#」是替換所有單詞開頭「字符串@「並以空格結束。


編輯,讓代碼在所有情況下工作(不更換電子郵件,不要替換空格通過@mvdc如指出,取代以「特殊字符」開頭的單詞,採用U按規定@mvdc)這應該在所需的情況下工作。

$string = "some text @person some other text\n 
some @pers\n 
@pess text [email protected] the email should not be replaced ,\n 
@[email protected] should be replaced , whitespaces not and \\n not"; 
var_dump(preg_replace('/\s\@.*\s/U', ' #replacement# ', $string)); 
exit; 

編輯,第4'修訂

$string = "@[email protected] some text @person some other [email protected]##[email protected] this can pass as an email 
some @pers\n 
@pess text [email protected] the email should not be replaced ,\n 
@[email protected] should be replaced , whitespaces not and \\n not @poelinca!"; 
var_dump(preg_replace('/(\s|^|\A)\@.*(\s|\Z|$)/U', ' #replacement# ', $string)); 
exit;