preg_replace_callback_array
執行正則表達式搜索並使用回調替換
preg_replace_callback_array()
函數返回一個字符串或字符串數組,其中一組正則表達式的匹配項被替換為回調函數的返回值。
注意:對於每個字符串,函數會按照給定的順序評估模式。在字符串上評估第一個模式的結果將作為第二個模式的輸入字符串,依此類推。這可能導致意外的行為。
展示一個句子中每個單詞包含多少字母或數字:
<?php function countLetters ( $matches ) { return $matches [ 0 ] . '[' . strlen ( $matches [ 0 ] ) . 'letter]' ; } function countDigits ( $matches ) { return $matches [ 0 ] . '[' . strlen ( $matches [ 0 ] ) . 'digit]' ; } $input = "There are 365 days in a year." ; $patterns = [ '/\b[az]+\b/i' => 'countLetters' , '/\b[0-9]+\b/' => 'countDigits' ] ; $result = preg_replace_callback_array ( $patterns , $input ) ; echo $result ; ?>
親自試一試
此例說明了按順序評估模式可能產生的潛在意外效果。首先,countLetters 替換會在"days" 後添加"[4letter]",執行該替換後,countDigits 替換會在"4letter" 中找到"4" 並添加"[1digit]":
<?php function countLetters ( $matches ) { return $matches [ 0 ] . '[' . strlen ( $matches [ 0 ] ) . 'letter]' ; } function countDigits ( $matches ) { return $matches [ 0 ] . '[' . strlen ( $matches [ 0 ] ) . 'digit]' ; } $input = "365 days" ; $patterns = [ '/[az]+/i' => 'countLetters' , '/[0-9]+/' => 'countDigits' ] ; $result = preg_replace_callback_array ( $patterns , $input ) ; echo $result ; ?>
親自試一試