在PHP中使用'@'字符后检查单词

use*_*226 11 php character

我现在正在制作新闻和评论系统,但我现在已经暂时停留在一个部分.我希望用户能够像@username那样引用Twitter风格的其他玩家.脚本看起来像这样:(不是真正的PHP,只是想象力脚本; 3)

$string = "I loved the article, @SantaClaus, thanks for writing!";
if($string contains @){ 
    $word = word after @;
    $check = is word in database? ...
}
Run Code Online (Sandbox Code Playgroud)

对于字符串中的所有@ username,也许用while()完成.我被卡住了,请帮忙.

And*_*ong 14

这是正则表达式的用武之地.

<?php
    $string = "I loved the article, @SantaClaus! And I agree, @Jesus!";
    if (preg_match_all('/(?<!\w)@(\w+)/', $string, $matches))
    {
        $users = $matches[1];
        // $users should now contain array: ['SantaClaus', 'Jesus']
        foreach ($users as $user)
        {
            // check $user in database
        }
    }
?>
Run Code Online (Sandbox Code Playgroud)
  1. /在开始和结束都是分隔符(不用担心这些现在).
  2. \w代表一个单词字符,其中包括a-z,A-Z,0-9,和_.
  3. (?<!\w)@有点先进,但它被称为负向后断言和手段"的@,它遵循单词字符." 这样您就不会包含电子邮件地址等内容.
  4. \w+手段,"一个或多个单词字符." 这+被称为量词.
  5. 括号周围的括号\w+ 捕获括号中的部分,并出现在$matches.

regular-expressions.info似乎是一个受欢迎的教程选择,但在网上有很多其他的.


And*_*eKR 6

看起来像preg_replace_callback()的工作:

$string = preg_replace_callback('/@([a-z0-9_]+)/', function ($matches) {
  if ($user = get_user_by_username(substr($matches[0], 1)))
    return '<a href="user.php?user_id='.$user['user_id'].'">'.$user['name'].'</a>';
  else
    return $matches[0];
}, $string);
Run Code Online (Sandbox Code Playgroud)