我现在正在制作新闻和评论系统,但我现在已经暂时停留在一个部分.我希望用户能够像@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)
/在开始和结束都是分隔符(不用担心这些现在).\w代表一个单词字符,其中包括a-z,A-Z,0-9,和_.(?<!\w)@有点先进,但它被称为负向后断言和手段"的@,它不遵循单词字符." 这样您就不会包含电子邮件地址等内容.\w+手段,"一个或多个单词字符." 这+被称为量词.\w+ 捕获括号中的部分,并出现在$matches.regular-expressions.info似乎是一个受欢迎的教程选择,但在网上有很多其他的.
看起来像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)
| 归档时间: |
|
| 查看次数: |
1409 次 |
| 最近记录: |