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[a-z]+\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 = [ '/[a-z]+/i' => 'countLetters', '/[0-9]+/' => 'countDigits' ]; $result = preg_replace_callback_array($patterns, $input); echo $result; ?>
亲自试一试