当用户发表评论时,我想抓住以@符号开头的每个单词。
离。 字符串是'检查出@ user1。它是@ user2和@ user3的照片。'
当我在PHP方面,我想抓住user1,user2,user3,然后我可以通知这些用户他们已在此评论中被标记。
我尝试使用strpos,但最接近的是如果字符串以@开头使用下面的逻辑。
if (0 === strpos($string, '@')){ echo 'yes' }
但这不是我需要的。
答案 0 :(得分:1)
您可以简单地使用此功能:
function get_tagged_users($comment) {
$matches = array();
if (preg_match_all('/@(\w+)\b/', $comment, $matches)) {
return $matches[1];
}
return array();
}
如果没有找到匹配项或者在执行正则表达式时发生错误,它将返回一个用户名数组(不带“@”)和一个空数组。
注意:它使用字边界和单词的常规定义。 Lorem @ipsum-ed dolor
只返回ipsum
。
因此,如果您需要在用户名中包含hypen( - ),只需使用/@([-\w]+)\b/
答案 1 :(得分:0)
这是一个正则表达式的方法:
$matches = [];
preg_match_all( "/@([-\w]+)\b/",
"Check this out @user1. It's a photo of @user2 and @user3",
$matches);
print_r($matches);
输出:
Array
(
[0] => Array
(
[0] => user1
[1] => user2
[2] => user3
)
)
正则表达式匹配@
后跟一个或多个字母数字字符或下划线(\w
)直到字边界(\b
)。匹配的单词位于$matches
(您可能已经猜到了)。
答案 2 :(得分:0)
A"正则表达式"和#34;无爆炸"溶液
$str = 'Check this out @user1. It\'s a photo of @user2 and @user3.';
$offset = 0;
$users = array();
$str .= ' ';
while($offset = strpos($str, '@', $offset + 1)){
$users[] = rtrim(substr($str, $offset + 1, strpos($str, ' ', $offset)- $offset), '?.,!:;');
}
print_r($users);
但是,假设您的用户名不包含空格和标点字符,以及标点符号后存在正确的空格。
我创建了一个快速的基准测试脚本来测试哪个答案最快。与我的观点相反,正则表达式似乎比手动进行位搜索更快。您可以自己查看结果here