2012-03-27 67 views
0

在字符串中找到@username的最佳方法是什麼?如何在字符串中查找@username?

起初我是根據@找到的字符串進行爆炸,但是看起來每個實例都經歷了很多麻煩。

我可以用正則表達式來查找字符串中的所有@usernames嗎?

+3

在http://stackoverflow.com/questions/4424179/twitter-username-regex-validation – danielrsmith 2012-03-27 14:08:41

回答

0

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

是當然的。正則表達式是正確的方式去:

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

看看嗯,做工不錯。但是,如果我在我的串中有@珍珠果醬,它只會撿起珍珠。有任何想法嗎? – Mike 2012-03-27 14:22:17

+0

@Mike我改變了正則表達式使用空格('\ s')作爲分隔符而不是字邊界('\ b'),因爲'-'也是正則表達式中的字邊界。它現在應該匹配'@ pearl-jam',但也會匹配'@foo(bar)' – Kaii 2012-03-27 14:29:56