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 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM