masterhoo masterhoo - 2 years ago 79
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


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

//user exists (link to profile)
$imatch="<a href='?s=$id_$user'>@".$match."</a>";
//user NOT exists (NOT link to profile)
$imatch ="@$match";
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 Source

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) {
    // replace exact username with new markup
    $string=preg_replace("/@" . $match . "(?=\s|$|,|\.)/", $imatch, $string);   

echo $string;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download