用数据库中的值替换表单输入中的@tags

Replacing @tags from form input with values from the database

我正在编写一个@tagging 系统,其中有人在评论框中张贴一些文本,例如:请@mike 阅读此内容。 @保罗也是。然后注释出现,@tags 替换为从包含@tags 及其实际值的特定数据库中选择的值。然后评论如下所示:请 Mike Smith 阅读此内容。保海也。 @tags 将替换为数据库中的值。

这是我目前所做的。

$comments = "Please @mike read this. @paul also";
$pattern = '/\B@[^\B]+/';
preg_match_all($pattern, $comments, $matches);
foreach ($matches[0] as $key => $value) {

$sql = "SELECT * FROM user_table WHERE tagged = '$value[$key]'";
foreach ($pdo ->query($sql) as $row){
$name = $row['name'];
$username = $row['username'];
$comments = preg_replace('/[@]+([A-Za-z0-9-_]+)/', '<a href='.$username.'>'.$name.'</a>', $comments );
}
echo $comments;}

到目前为止,这并没有输出任何合理的东西,而是它给出的只是简单的注释。 请在必要时纠正我。谢谢大家

您的初始 preg_match 正则表达式模式与您要查找的内容不符。

应该是这样的:

$pattern = '/@[a-zA-Z0-9_]+/';

那么 $matches 的值如下:

array(1) { 
  [0]=> array(2) { 
    [0]=> string(5) "@mike" 
    [1]=> string(5) "@paul" 
  } 
}

所以您只需要删除 @ 符号,除非您的用户名与它们一起存储在数据库中。您的 foreach 看起来更像这样:

foreach ($matches[0] as $match) {
  $match = trim($match,'@'); // remove @ sign
  $sql = "SELECT * FROM user_table WHERE tagged = :username";
  $results = $pdo->fetchAll($sql, ['username' => $match]);
  // now run foreach on $results...
}

试试这个

$comments = "Please @mike read this. @paul also";
$pattern = '/@[a-zA-Z0-9_]+/'; # Changed
preg_match_all($pattern, $comments, $matches);

# print_r($matches[0]); --Output> Array ( [0] => @mike [1] => @paul )

foreach ($matches[0] as $key => $value) {   

    $newValue = str_replace('@'," ", $value);# added

    # echo $newValue; --Output> mike paul

    $sql = "SELECT * FROM user_table WHERE tagged = '$newValue' "; # Changed

    foreach ($pdo->query($sql) as $row){

        $name = $row['name'];
        $username = $row['username'];
        $link = "<a href=".$username.">".$name."</a>"; # added
        $comments = preg_replace('@', $link, $comments );

    }

    echo $comments;

}