2016-05-22 63 views
0

我有那些MySQL用戶檢索Twitter的鏈接PHP

1 master 
2 mastercard 
3 mastercom 

在接下來的字符串,我想將它們鏈接到自己的配置文件的用戶(@user)

$string=" Hi, I would like to met up with @master @mastercard @mastercom and @masterhigh "; 

哪裏@ masterhigh不屬於mysql表,不需要鏈接到他的配置文件。

我有這樣的代碼

preg_match_all('/@(\w+)/',$string,$matches); 

foreach ($matches[1] as $match) { 
    // 
$user=mysql_query("SELECT id_user FROM $table_users WHERE username='$match' LIMIT 1"); 
$user_n=mysql_fetch_array($user); 
    //num 
    $user_num=mysql_num_rows($user); 
    $id_user=$user_n['id_user']; 

if($user_num>0){ 
//user exists (link to profile) 
$imatch="<a href='?s=$id_$user'>@".$match."</a>";  
}else{ 
//user NOT exists (NOT link to profile) 
$imatch ="@$match"; 
}  
$string=str_replace("@".$match,$imatch,$string);  
} 
echo $string; 

雖然用戶型動物,一切都OK了,但它們具有相同的字母開始時,代碼只鏈接重複字母(@Master),而不是重定向到@萬事達卡配置文件或@mastercom配置文件。我認爲str_replace()不能按預期工作。我做錯了什麼? 5星。

回答

0

首先不使用mysql_ *函數它們已被棄用。其次。 str_replace替換從第一次匹配開始的字符串中的所有出現。所以@mastercard變成@mastercard,並且@mastercard永遠不會被替換。在你的正則表達式中更好地搜索空間,標籤,endofstring等,然後用相同的正則表達式替換它們。爲簡單起見修改代碼:

$string=" Hi, I would like to met up with @master @mastercard @mastercom and @masterhigh, @masterhigher. and all other @mesters"; 

// Serch for whitespace or other char after username 
preg_match_all('/@(\w+)(?=\s|$|,|\.)/', $string, $matches); 

foreach ($matches[1] as $match) { 
    $imatch="<b>@".$match."</b>"; 
    // replace exact username with new markup 
    $string=preg_replace("/@" . $match . "(?=\s|$|,|\.)/", $imatch, $string); 
} 

echo $string; 
+0

這是正則表達式'(?= \ s | $ |,| \。)/'替換任何分隔符嗎?或只有點,美元和逗號? – masterhoo

+0

只有點和逗號,美元符號是正則表達式中的'字符串結尾'。你可以添加儘可能多的你想要使用或運算符'|',如果它是在正則表達式中的特殊字符前加'''(如我的例子中的點) –

+0

我相信你可以使用'\ @(\ w +)(? !\ w)\'pattern如果您不想列出所有可能的分隔符 –