我想搜索我的twitter狀態對象的文本屬性,並將,的@username換出。我到目前爲止所嘗試的看起來是這樣的:如何使用PHP preg_replace鏈接Twitter用戶名?
$pattern = '/([@]{1})([a-zA-Z0-9\_]+)/';
$replace = '<a href="http://twitter.com/\2">\1\2</a>';
$new_string = preg_replace($pattern, $replace, $text);
但它沒有做任何替換。我知道我的reg exp是錯誤的,但我無法弄清楚究竟在哪裏/爲什麼。幫幫我?
**編輯:...請求的樣本數據?
$text = '@janesmith I like that, but my friend @johndoe said it better.';
所需的輸出:
@janesmith我喜歡這樣,但我的朋友說:@johndoe更好。
***** MY FULL FUNCTION *****
function linkify($string, $twitter=false) {
// reg exp pattern
$pattern = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// convert string URLs to active links
$new_string = preg_replace($pattern, "<a href=\"\\0\">\\0</a>", $string);
if ($twitter) {
$pattern = '/@([a-zA-Z0-9_]+)/';
$replace = '<a href="http://twitter.com/\1">@\1</a>';
$new_string = preg_replace($pattern, $replace, $new_string);
}
return $new_string;
}
你能提供一個輸入樣本和所需的輸出嗎? – LarsH 2010-10-28 14:53:23
你可以把一些樣本數據進行測試嗎? – Keng 2010-10-28 14:53:31
當你說「它不做任何替換」時,你的意思是它刪除了用戶名,但沒有鏈接,或者你的意思是它沒有修改輸入字符串? – LarsH 2010-10-28 15:03:28