2011-03-30 104 views
1

我想提取所有以@开头的单词以字符串形式与php。从字符串中提取以字母开头的单词

哪种方式最好?

编辑:我不想去取邮件

感谢

+0

你如何定义一个字? – codaddict 2011-03-30 15:42:07

+0

我的意思是@ahmetvardar – 2011-03-30 15:42:42

+0

那么空格分隔这个词?匹配'@纽约'将获取'@ New',对吗? – 2011-03-30 15:43:40

回答

8
$matches = null; 
preg_match_all('/(?!\b)(@\w+\b)/','This is the @string to @test.',$matches) 

使用preg_match_all并采取前瞻的单词的开始((?!\b))和字分隔符(\b)的优势,你可以轻松实现这一点。分解:

/   # beginning of pattern 
    (?!\b) # negative look-ahead for the start of a word 
    (  # begin capturing 
    @  # look for the @ symbol 
    \w+  # match word characters (a-z, A-Z, 0-9 & _) 
    \b  # match until end of the word 
)   # end capturing 
/   # end of pattern 

demo

+0

'$ matches = null;'是不需要的。 – codaddict 2011-03-30 15:48:05

+0

@codeaddict。我知道,但我认为知道我的变量在哪里开始是更好的做法。尽管块范围实际上不在*那里,我在.NET和PHP之间,并且想知道在哪里可以看到新的变量。 – 2011-03-30 15:49:37

+0

你也可以使用'\ B'而不是'(?!\ b)'。 – Gumbo 2011-03-30 15:51:17

相关问题