我现在正在制作新闻和评论系统,但我现在已经停留了一段时间。我希望用户能够引用推特风格的其他玩家,如 @username 。该脚本将如下所示:(不是真正的PHP,只是想象力脚本; 3)
$string = "I loved the article, @SantaClaus, thanks for writing!";
if($string contains @){
$word = word after @;
$check = is word in database? ...
}
对于字符串中的所有@ username,也许是用while()完成的。我被困了,请帮忙。
答案 0 :(得分: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
}
}
?>
/
是分隔符(暂时不要担心这些)。\w
代表字符,其中包括a-z
,A-Z
,0-9
和_
。(?<!\w)@
有点高级,但它被称为负面后瞻断言,意味着“<{1>} 不关注一个字的字符。“这样您就不会包含电子邮件地址等内容。@
表示“一个或多个单词字符”。 \w+
称为量词。+
周围的括号捕获括号内的部分,并显示在\w+
。regular-expressions.info似乎是一个受欢迎的教程选择,但还有很多其他人在线。
答案 1 :(得分: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);
答案 2 :(得分:3)
考虑使用Twitter API来捕获文字中的用户名:https://github.com/twitter/twitter-text-js
答案 3 :(得分:2)
这是一个符合您需要的表达式,但不会捕获电子邮件地址:
$str = '@foo I loved the article, @SantaClaus, thanks for writing to my@email.com';
preg_match_all('/(^|[^a-z0-9_])(@[a-z0-9_]+)/i', $str, $matches);
//$matches[2][0] => @foo
///$matches[2][1] => @SantaClause
如您所见:my@email.com未被捕获,但@ foo和@SantaClaus字符串 ...