doulin1867 2013-05-02 14:12
浏览 12
已采纳

preg_replace具有相似的值

I am working on a mentions system and I have run across a problem, when I am looping through and changing the mentions to links, it will replace similar ones such as @tom and @tom123 with the same link to /tom/ instead of individual.

I have tried using regex and preg_replace however I am also checking to see if the username actually exists, so I am just wondering if there is a way I can prevent it from happening.

$tweet = "@wayne how are you? @wayne123 is cool but are you?";

        preg_match_all('/(^|\s)@([a-z0-9_]+)/i', $tweet, $matches);
        $i = 0;

        foreach( $matches[2] as $value ) 
        {   

            if ( $db_query )
            {
                $tweet = str_replace("@" . $value, "<a href=\"/user/$value\">@$value</a>!", $tweet);
            }               
        }

        echo $tweet; // outputs: hi <a href="/user/wayne">@wayne!</a> how are you? <a href="/user/wayne">@wayne!</a>123 is cool but are you?

Any help is greatly appreciated, I have tried with regex before but it continues along the line and updates the others before I am even able to check to see if they are a valid user

  • 写回答

3条回答 默认 最新

  • dongzh1988 2013-05-02 14:38
    关注

    The problem is that the first time through your loop @wayne123 is replaced with @wayne so it can't find a match for the second time through the loop.

    Use preg_replace with back references.

    $tweet = "@wayne how are you? @wayne123 is cool but are you?";
    $pattern = '/(^|\s)@(\w+)/';
    $replacement = '<a href="/user/$2">@$2</a>';
    print preg_replace($pattern, $replacement, $tweet);
    

    in $replacement the $2 is replaced with the match of the second set of parenthesis (\w)

    Note that (\w) is the shorthand for ([a-zA-Z0-9_])

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算