【发布时间】:2020-05-14 17:10:57
【问题描述】:
我创建了这个函数来检查提到的@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
@dog 也没有,@turtled 被替换...尽管它们在数据库中..
做错了什么?
【问题讨论】:
-
你需要将
return $string移动到foreach右括号}之后 -
是的,我试过了。它也不起作用。谢谢
-
如果您只想匹配整个单词,请使用
\b而不是(?!\w) -
在每个循环结束时(以前的返回位置)尝试
echo $string.PHP_EOL; -
@Barmar 谢谢。伟大的洞察力。我已经编辑了帖子。以及关于我的问题的任何线索。我还是找不到办法。
标签: php preg-replace preg-match-all