masterhoo masterhoo - 6 months ago 14
MySQL Question

retrieving twitter like usename links php

I have those mysql users

1 master
2 mastercard
3 mastercom


In the next string , I want to link them to his own profile the users (@user)

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


where @masterhigh doesnt belong to the mysql table and need no to be linked to his profile.

I have this code

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;


While the users are differents, everything is Ok, but when they starts with the same letters, the code only links the repeated letters (@master) and not redirect to @mastercard profile or @mastercom profile. I think str_replace() is not working as expected. What I am doing wrong? 5 stars.

Answer

Firstly do not use mysql_* functions they are deprecated. Secondly. str_replace replaces all occurences in string starting from first match. so @mastercard becomes @mastercard, and @mastercard get never replaced. Better search for space, tab, endofstring etc. in Your regexp, and then replace them with same regexp. Code modified for simplicity purposes:

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