Функция PHP preg_replace_callback()
❮ Справочник по регулярному выражению PHP
Пример
Сосчитай буквы во всех словах предложения:
<?php
function countLetters($matches) {
return $matches[0] . '(' .
strlen($matches[0]) . ')';
}
$input = "Welcome to W3Schools.com!";
$pattern = '/[a-z0-9\.]+/i';
$result = preg_replace_callback($pattern,
'countLetters', $input);
echo $result;
?>
Определение и использование
Функция preg_replace_callback()
, учитывая выражение и обратный вызов, возвращает строку, в которой все совпадения выражения заменяются подстрокой, возвращаемой функцией обратного вызова.
Синтаксис
preg_replace_callback(pattern, callback, input, limit, count)
Значения параметров
Parameter | Description |
---|---|
pattern | Required. A regular expression or array of regular expressions indicating what to search for |
replacements | Required. A callback function which returns the replacement. The callback function has one parameter containing 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: | 4.0.5+ |
Список изменений: | PHP 5.1.0 - Добавлен параметр count |
❮ Справочник по регулярному выражению PHP