【问题标题】:How to find @username in a string?如何在字符串中找到@username?
【发布时间】:2012-03-27 14:06:17
【问题描述】:

在字符串中找到@username 的最佳方法是什么?

起初我是根据找到的@ 来分解字符串,但遍历每个实例似乎都很麻烦。

我可以使用正则表达式来查找字符串中的所有@usernames 吗?

【问题讨论】:

标签: php regex string


【解决方案1】:

当然可以。正则表达式是正确的方法:

if (preg_match_all('!@(.+)(?:\s|$)!U', $text, $matches))
    $usernames = $matches[1];
else
    $usernames = array(); // empty list, no users matched

【讨论】:

  • 嗯,运行良好。但如果我的字符串中有@pearl-jam,它只会捡起珍珠。有什么想法吗?
  • @Mike 我将正则表达式更改为使用空格 (\s) 作为分隔符而不是单词边界 (\b),因为 - 也是正则表达式中的单词边界。它现在应该匹配@pearl-jam,但也将匹配@foo(bar)
【解决方案2】:

你可以使用 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";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多