preg_match_all仅替换第一次出现的@user php

问题描述 投票:0回答:1

我创建了此功能来检查提到的@users

function user_links($string,$table_users,$pdo) {
    preg_match_all('/@(\w+)/',$string,$matches);
           //
        $sql="
      SELECT id_user,user 
      FROM $table_sers 
      WHERE user= :user LIMIT 1";
        $sql = $pdo->prepare($sql); 
        $sql->bindParam(':user', $match,PDO::PARAM_STR, 20); 

    foreach ($matches[1] as $match) {

        $sql->execute();

        $res = $sql->fetch(PDO::FETCH_ASSOC);

        if($sql->rowCount() > 0){
            $id_user=$res['id_user'];
            $user=$res['user'];

            $from = "/@(" . $match . ")(?!\w)/";
            $to = "<a href='user.phhp?id=$id_user'>@".$match."</a>";
            $string = preg_replace($from, $to, $string);
        }

        return $string;
    }
}

我正在尝试将所提到的用户与下一个string链接,但它仅替换第一次出现的事件...

@cat,@dog and @turtle is in the db

主字符串

 $string="Hi Im @cat and not @cat2, yes you are @dog, @squirrel and @turtle ";

   echo user_links($string,$table_users,$pdo);

它检索到的内容:

//Hi Im <a>@cat</a> and not @cat2, yes you are @dog, @squirrel and @turtle 

@狗都没有,@ turtled都被替换了...尽管它们在数据库中。

做错了什么?

我已创建此函数来检查上述@users函数user_links($ string,$ table_users,$ pdo){preg_match_all('/ @(\ w +)/',$ string,$ matches); // $ sql =“ SELECT ...

php preg-replace preg-match-all
1个回答
0
投票

首先,您可以动态创建查询以查找所有ID,因此您无需循环进行字符串替换。

© www.soinside.com 2019 - 2024. All rights reserved.