显示句子中每个单词有多少个字母或数字:
<?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)
Parameter | Description |
---|---|
pattern | Required. An associative array which associates regular expression patterns to callback functions. The callback functions have one parameter which is an array of matches.The first element in the array contains the match for the whole expression while the remaining elements have matches for each of the groups in the expression. |
input | Required. The string or array of strings in which replacements are being performed |
limit | Optional. Defaults to -1, meaning unlimited. Sets a limit to how many replacements can be done in each string |
count | Optional. After the function has executed, this variable will contain a number indicating how many replacements were performed |
返回值: | 返回对输入字符串或多个字符串应用替换后得到的字符串或字符串数组 |
---|---|
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;
?>
亲自试一试 »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!