开发者

How to create mentions for names like "@myname" using javascript?

I'm planning to build web app and i heve question how to create mentions for name "@myname" like facebook or twitte开发者_开发知识库r


Find them in a string with this regex....

$str = 'Yo @bob, what\'s up? I have a new email, tom@bob.com, tell @john too, from @alex';

preg_match_all('/\s@(?P<mention>\w+?)\b/', $str, $mentions);

var_dump($mentions);

Output

array(3) {
  [0]=>
  array(3) {
    [0]=>
    string(5) " @bob"
    [1]=>
    string(6) " @john"
    [2]=>
    string(6) " @alex"
  }
  ["mention"]=>
  array(3) {
    [0]=>
    string(3) "bob"
    [1]=>
    string(4) "john"
    [2]=>
    string(4) "alex"
  }
  [1]=>
  array(3) {
    [0]=>
    string(3) "bob"
    [1]=>
    string(4) "john"
    [2]=>
    string(4) "alex"
  }
}

Of course, you could real time detect them in a string in JavaScript, just change that regex to a JavaScript one.

Then, you would look up your database based on the tagged name, and then do what you need to do!

You could cut down on requests by limiting your regex to what makes a valid username, e.g. /\w{6,}/.


function mention($txt)
{
    $txt = ' '.$txt;
    preg_match_all('/\s@(?P<mention>\w+?)\b/', $txt, $mentions);
    echo "<pre>";
    print_r($mentions);
    if (isset($mentions[0])) {
        foreach ($mentions[0] as $key => $value) {
            $mention = strtolower(str_replace(array("@"," "), "", $value));
            $txt = str_replace($value, ' <a href="/'.$mention.'">'.$mention.'</a>', $txt);
        }
    }
    return trim($txt);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜