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)
매개변수 값
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;
?>
❮ PHP RegExp 참조