duanhao9176 2016-05-22 13:52
浏览 61
已采纳

检索twitter就像usename链接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.

  • 写回答

1条回答 默认 最新

  • dongpan1365 2016-05-22 15:12
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择