2011-02-17 63 views
1

有人能解釋是什麼正則表達式的意思是: '/ &w; /'

preg_replace('/&\w;/', '', $buf) 

這是否有什麼功能?我看過各種教程,發現它用字符串''取代/&\w;/的模式。但我無法理解/&\w;/的模式。它代表什麼?

同樣在

preg_match_all("/(\b[\w+]+\b)/", $buf, $words) 

我不明白什麼是字符串"/(\b[\w+]+\b)/"代表。

請幫忙。在此先感謝:)

+0

對不起@Codeur,@Gordon你是正確的。我將加入http://www.regular-expressions.info/下面的建議作爲開始的好地方。 – 2011-02-17 13:34:21

回答

1

在正則表達式中,\ w代表任何「單詞」字符。即:a-z,A-Z,0-9和下劃線。 \ b代表「單詞邊界」,即單詞的開始和結尾(一系列單詞字符)。

因此,/&\w;/是一個正則表達式,用於匹配&符號,後跟一系列單詞字符,後跟一個;。例如,&foobar;會匹配,並且preg_replace將用空字符串替換它。

以同樣的方式,/(\b[\w+]+\b)/匹配單詞邊界,後跟多個單詞字符,後跟另一個單詞邊界。單詞使用括號分開記錄。所以,這個正則表達式只會將字符串中的單詞作爲數組返回。

+0

's/a series/a single /`在第二段中。 – 2011-02-17 13:41:30

11

你的第一個表達式的解釋很簡單,那就是:

&  # Match the character 「&」 literally 
\w # Match a single character that is a 「word character」 (letters, digits, and underscores) 
;  # Match the character 「;」 literally 

第二個是:

(   # Match the regular expression below and capture its match into backreference number 1 
    \b   # Assert position at a word boundary 
    [\w+]  # Match a single character present in the list below 
        # A word character (letters, digits, and underscores) 
        # The character 「+」 
     +   # Between one and unlimited times, as many times as possible, giving back as needed (greedy) 
    \b   # Assert position at a word boundary 
) 

preg_replace功能使得使用正則表達式。正則表達式允許您以非常強大的方式在文本中查找模式。

爲了能夠使用像preg_replacepreg_match這樣的函數,我建議您首先看看正則表達式的工作方式。

可以收集在這個網站http://www.regular-expressions.info/

大量的信息,您還可以使用軟件工具來幫助你瞭解正則表達式(如RegexBuddy

相關問題