簡體   English   中英

有人可以用PHP解釋此代碼段嗎?

[英]Can someone explain this code snippet in PHP?

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

我從未用過這種正則表達式,它如何工作?

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

這里的第一個和第二個參數是相同大小的數組,就像您為數組的每個$ element調用preg_replace一樣。

其次, /通常是模式定界符,但實際上您可以使用任何字符,只需將其用作第一個字符及其定界符即可。 (在#一個模式中使用#

在替換字符串中, \\\\1 (轉義為\\1 )表示匹配的第一個括號的內容, \\2為第二個匹配的內容。

在這種情況下, \\1.?匹配的是什么.? 第一個模式中的\\2是第二個模式中的`。\\匹配

'::'.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

請注意, ^匹配輸入的開頭, 而不是文字^

還能用嗎?

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

結果:

Http:::/google.com::

preg_replace的文檔中可以找到它的大多數“工作原理”。 它使用數組形式進行多次替換(請參見示例2)。 它使用e開關執行PHP代碼,而不是替換字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM