2011-03-30 105 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

相關問題