【问题标题】:How to detect usernames in a comment using preg_match?如何使用 preg_match 检测评论中的用户名?
【发布时间】:2015-08-30 03:46:44
【问题描述】:

我正在尝试设计一个评论/回复系统,就像 stackoverflow 中的系统一样,如果在评论中提到@username,则会向他发送通知。

以评论为例

$comment="hello @myname and @my-name and @my+name and @my%name and @my&name and @my_name and @my name @my/name and @3535 and @12";

问题是我的代码

        if(preg_match('~@([^\s]+)~', $comment, $matches)){
            print_r($matches);
        }

只查找用户名@myname。有没有办法解决这个问题,以便它检测到所有用户名?

此外,上面评论中提到的哪些用户名是 stackoverflow 中的有效用户名,例如 my-namemy%name 有效用户名,当它们在 stackoverflow 评论中被提及时被检测到。

最后,是否可以将我的评论示例中的每个有效username 替换为<strong>username</strong>

【问题讨论】:

标签: php regex string text


【解决方案1】:

您的代码的问题是 preg_match() 函数找到第一个匹配的模式并返回 truefalse 而没有沿着字符串的其余部分继续前进。所以它不会通过下一个用户名。 为此,将 preg_match() 条件包装在一个循环中可能很划算。

这段代码应该可以完成!

$comment="hello @myname and @my-name and @my+name and @my%name and @my&name and @my_name and @my name @my/name and @3535 and @12";

$comment_arr = explode(' ', $comment);

// echo '<pre>';
// print_r($comment_arr);
// echo '</pre>';

$usernames = [];
$new_comment_arr = [];

for ($i=0; $i < count($comment_arr) ; $i++) 
{
    if( preg_match('/^@(.*)/', $comment_arr[$i]) ) 
    {
        array_push($usernames, $comment_arr[$i]);   // push the usernames
        array_push($new_comment_arr, '<strong>'.$comment_arr[$i].'</strong>');  // push the usernames with '<strong>' wrapped around in the new comments array
    }
    else
        array_push($new_comment_arr, $comment_arr[$i]);     // push the unmatched words(other words) in the new comments array
}

echo '<pre>';
print_r($new_comment_arr);
print_r($usernames);
echo '</pre>';

$new_comment = implode(' ', $new_comment_arr);  // implode the new array

echo $new_comment;  // the new comment with '<strong>' wrapped around the usernames

不应允许使用用户名 @my name。 在某些情况下,如果您希望用户名位于 URL 中,则此类用户名将转换为 @my%20name

也不允许在用户名中使用“/”,因为如果您重写 URL,它将被视为参数并可能导致 404 错误。

就我而言,您应该只允许在用户名中使用字母、数字和下划线('_')。

【讨论】:

    【解决方案2】:

    为什么不试试 cmets 的社交插件

    我建议你为 cmets 使用 Facebook 插件

    更多详情http://developers.facebook.com/docs/plugins/comments

    【讨论】:

      【解决方案3】:

      我认为您必须在数组中收集所有以 sat char @ 开头的名称,以便您可以将数组用于您想要的所有内容,例如通过循环数组向所有人发送通知。 我已经制作了一个代码来适应它。

      <?php
          $comment="hello @myname and @my-name and @my+name and @my%name and @my&name and @my_name and @my name @my/name and @3535 and @12";
          $keywords = preg_split("/[\s]+/", $comment);
          foreach($keywords as $row=>$value){
              if(preg_match("/^@/",$value)==0){
                  unset($keywords[$row]);
              }
          }
          print_r($keywords);
      ?> 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-24
        • 1970-01-01
        • 1970-01-01
        • 2018-07-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多