PHP preg_replace_callback() 함수
예시
문장에 있는 모든 단어의 글자 수 세기:
<?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 RegExp 참조