정규식(PCRE) preg_replace_callback
(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)
preg_replace_callback — 정규식 검색을 수행하고 콜백을 사용하여 바꾸기
설명
preg_replace_callback( string|array $pattern, callable $callback, string|array $subject, int $limit = -1, int &$count = null, int $flags = 0 ): string|array|null
이 함수의 동작은 replacement
매개변수 대신 callback
을 지정해야 한다는 사실을 제외하고 preg_replace()와 거의 동일합니다.
매개변수
pattern
- 검색할 패턴입니다. 문자열이거나 문자열이 있는 배열일 수 있습니다.
callback
subject
문자열에서 일치하는 요소의 배열을 호출하고 전달하는 콜백입니다. 콜백은 대체 문자열을 반환해야 합니다. 다음은 콜백 서명입니다.handler(array
$matches
): string종종 한 곳에서 preg_replace_callback()에 대한
callback
함수가 필요합니다. 이 경우 anonymous function를 사용하여 preg_replace_callback() 호출 내에서 콜백을 선언할 수 있습니다. 이렇게 하면 호출에 대한 모든 정보를 한 곳에서 얻을 수 있고 다른 곳에서는 사용되지 않은 콜백 함수 이름으로 함수 네임스페이스를 어지럽히지 않습니다.예제 #1 preg_replace_callback() 및 익명 함수
<?php /* a unix-style command line filter to convert uppercase * letters at the beginning of paragraphs to lowercase */ $fp = fopen("php://stdin", "r") or die("can't read stdin"); while (!feof($fp)) { $line = fgets($fp); $line = preg_replace_callback( '|
\s*\w|', function ($matches) { return strtolower($matches[0]); }, $line ); echo $line; } fclose($fp); ?>
subject
- 검색하고 바꿀 문자열 또는 문자열이 있는 배열입니다.
limit
- 각
subject
문자열의 각 패턴에 대해 가능한 최대 대체. 기본값은-1
(제한 없음)입니다. count
- 지정된 경우 이 변수는 수행된 교체 수로 채워집니다.
flags
flags
는 일치 배열의 형식에 영향을 미치는PREG_OFFSET_CAPTURE
및PREG_UNMATCHED_AS_NULL
플래그의 조합일 수 있습니다. 자세한 내용은 preg_match()의 설명을 참조하십시오.
반환 값
preg_replace_callback()은 subject
매개변수가 배열이면 배열을 반환하고 그렇지 않으면 문자열을 반환합니다. 오류 시 반환 값은 null
입니다.
일치하는 항목이 발견되면 새 제목이 반환되고, 그렇지 않으면 subject
이 변경되지 않고 반환됩니다.
오류/예외
전달된 정규식 패턴이 유효한 정규식으로 컴파일되지 않으면 E_WARNING
이 발생합니다.
변경 로그
버전 | 설명 |
---|---|
7.4.0 | 플래그 매개 변수가 추가되었습니다. |
Examples
예제 #2 preg_replace_callback() 예제
<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// the callback function
function next_year($matches)
{
// as usual: $matches[0] is the complete match
// $matches[1] the match for the first subpattern
// enclosed in '(...)' and so on
return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
"|(\d{2}/\d{2}/)(\d{4})|",
"next_year",
$text);
?>
위의 예는 다음을 출력합니다.
April fools day is 04/01/2003 Last christmas was 12/24/2002
예제 #3 캡슐화된 BB 코드를 처리하기 위해 재귀 구조를 사용하는 preg_replace_callback()
<?php
$input = "plain [indent] deep [indent] deeper [/indent] deep [/indent] plain";
function parseTagsRecursive($input)
{
$regex = '#\[indent]((?:[^[]|\[(?!/?indent])|(?R))+)\[/indent]#';
if (is_array($input)) {
$input = '<div style="margin-left: 10px">'.$input[1].'</div>';
}
return preg_replace_callback($regex, 'parseTagsRecursive', $input);
}
$output = parseTagsRecursive($input);
echo $output;
?>
기타
- PCRE Patterns
- preg_replace_callback_array() - 정규식 검색을 수행하고 콜백을 사용하여 바꾸기
- preg_quote() - 정규 표현식 문자 인용
- preg_replace() - 정규식 검색 및 바꾸기 수행
- preg_last_error() - 마지막 PCRE 정규식 실행의 오류 코드를 반환합니다.
- 익명 함수