PHP 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[a-z]+\b/i' => 'countLetters',
'/\b[0-9]+\b/' => 'countDigits'
];
$result = preg_replace_callback_array($patterns, $input);
echo $result;
?>
自己動手試一試 »
定義和用法
preg_replace_callback_array()
函式返回一個或多個字串,其中一組正則表示式的匹配項被回撥函式返回值替換。
注意:對於每個字串,函式按給定順序評估模式。第一個模式處理字串的結果將作為第二個模式的輸入字串,依此類推。這可能導致意外的行為。
語法
preg_replace_callback_array(patterns, input, limit, count)
引數值
引數 | 描述 |
---|---|
pattern | 必需。一個關聯陣列,將正則表示式模式與回撥函式關聯起來。 回撥函式有一個引數,即一個匹配項陣列。陣列的第一個元素包含整個表示式的匹配項,而其餘元素包含表示式中每個組的匹配項。 |
input | 必需。執行替換的字串或字串陣列 |
limit | 可選。預設為 -1,表示不限制。設定在每個字串中可以執行的替換次數 |
count | 可選。函式執行後,此變數將包含一個數字,指示執行了多少次替換 |
技術詳情
返回值 | 返回透過將替換應用於輸入字串或字串而產生的字串或字串陣列 |
---|---|
PHP 版本 | 7+ |
更多示例
示例
此示例說明了模式按順序評估可能產生的意外效果。首先,countLetters 替換將 "[4letter]" 新增到 "days" 中,在執行該替換後,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 = [
'/[a-z]+/i' => 'countLetters',
'/[0-9]+/' => 'countDigits'
];
$result = preg_replace_callback_array($patterns, $input);
echo $result;
?>
自己動手試一試 »
❮ PHP 正則表示式參考