有人可以用PHP解释这段代码片段吗?

时间:2010-03-02 20:45:46

标签: php regex

preg_replace(array('#/(.?)#e', '/(^|_|-)+(.)/e'), 
            array("'::'.strtoupper('\\1')", "strtoupper('\\2')"), $text);

我从未以这种方式使用正则表达式,它是如何工作的?

3 个答案:

答案 0 :(得分:2)

通常是:preg_replace('/pattern/flags', $replacement, $text)

这里的第一个和第二个参数是相同大小的数组,就像你为数组的每个$元素调用preg_replace一样。

其次,/通常是模式分隔符,但实际上您可以使用任何字符,只需将其用作第一个字符及其分隔符。 (这里#用于第一种模式)

在替换字符串中,\\1\1转义)表示匹配的第一个括号的内容和\2是第二个匹配。< / p>

在这种情况下,\1.?在第一种模式中匹配的内容,\2是在第二种模式中匹配的。\匹配

答案 1 :(得分:1)

/(.?)'::'.strtoupper('\\1')匹配的内容替换为\1替换为正则表达式组1中匹配的内容:(.?)

并将(^|_|-)+(.)strtoupper('\\2')匹配的内容替换为\2替换为正则表达式组2中匹配的内容:(.)

正则表达式#1:/(.?)表示:

/       # match the character '/'
(       # start capture group 1
  .?    #   match any character except line breaks and match it once or none at all
)       # end capture group 1

和正则表达式#2:(^|_|-)+(.)表示:

(      # start capture group 1
  ^    #   match the beginning of the input
  |    #   OR
  _    #   match the character '_'
  |    #   OR
  -    #   match the character '-'
)+     # end capture group 1 and repeat it one or more times
(      # start capture group 2
  .    #   match any character except line breaks
)      # end capture group 2

请注意^匹配输入的开头,文字^

答案 2 :(得分:0)

它甚至可以工作吗?

echo camelize('http://google.com/');

结果:

Http:::/google.com::

preg_replace的文档中可以找到大多数“工作原理”。它使用数组形式进行多次替换(参见示例2)。它使用e开关来执行PHP代码,而不是替换字符串。

相关问题