2011-02-17 142 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

相关问题