【发布时间】:2012-03-27 14:06:17
【问题描述】:
在字符串中找到@username 的最佳方法是什么?
起初我是根据找到的@ 来分解字符串,但遍历每个实例似乎都很麻烦。
我可以使用正则表达式来查找字符串中的所有@usernames 吗?
【问题讨论】:
在字符串中找到@username 的最佳方法是什么?
起初我是根据找到的@ 来分解字符串,但遍历每个实例似乎都很麻烦。
我可以使用正则表达式来查找字符串中的所有@usernames 吗?
【问题讨论】:
当然可以。正则表达式是正确的方法:
if (preg_match_all('!@(.+)(?:\s|$)!U', $text, $matches))
$usernames = $matches[1];
else
$usernames = array(); // empty list, no users matched
【讨论】:
\s) 作为分隔符而不是单词边界 (\b),因为 - 也是正则表达式中的单词边界。它现在应该匹配@pearl-jam,但也将匹配@foo(bar)
你可以使用 strpos() 代替
供参考http://php.net/manual/en/function.strpos.php
$pos = strpos($mystring, $findme);
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
【讨论】: