我有那些mysql用户

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;


尽管用户不同,但是一切正常,但是当他们以相同的字母开头时,代码仅链接重复的字母(@master),而不重定向到@mastercard配置文件或@mastercom配置文件。我认为str_replace()无法正常工作。我做错了什么? 5星。

最佳答案

首先,不要使用不推荐使用的mysql_ *函数。
其次。 str_replace替换字符串中从第一个匹配项开始的所有出现。因此@mastercard变成@mastercard,而@mastercard永远不会被替换。更好地在您的regexp中搜索空格,制表符,endofstring等,然后用相同的regexp替换它们。为了简单起见,修改了代码:

$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;

10-01 04:55