當前位置: 首頁> 函數類別大全> preg_replace_callback_array

preg_replace_callback_array

執行正則表達式搜索並使用回調替換
名稱:preg_replace_callback_array
分類:正則處理PCRE
所屬語言:php
一句話介紹:給定將表達式與回調函數關聯的數組,返回字符串,其中每個表達式的所有匹配項都替換為回調函數返回的子字符串。

定義和用法

preg_replace_callback_array()函數返回一個字符串或字符串數組,其中一組正則表達式的匹配項被替換為回調函數的返回值。

注意:對於每個字符串,函數會按照給定的順序評估模式。在字符串上評估第一個模式的結果將作為第二個模式的輸入字符串,依此類推。這可能導致意外的行為。

實例

例子1

展示一個句子中每個單詞包含多少字母或數字:

 <?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 ;
?>

親自試一試

例子2

此例說明了按順序評估模式可能產生的潛在意外效果。首先,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 ;
?>

親自試一試

同類函數