정규식(PCRE) preg_match_all

(PHP 4, PHP 5, PHP 7, PHP 8)

preg_match_all — 전역 정규식 일치 수행


설명

preg_match_all(
    string $pattern,
    string $subject,
    array &$matches = null,
    int $flags = 0,
    int $offset = 0
): int|false
                

pattern에 지정된 정규 표현식과 일치하는 모든 항목에 대해 subject를 검색하고 flags에 지정된 순서대로 matches에 넣습니다.

첫 번째 일치 항목이 발견된 후 마지막 일치 항목의 끝에서 후속 검색이 계속됩니다.


매개변수

pattern
문자열로 검색할 패턴입니다.
subject
입력 문자열입니다.
matches
flags에 따라 정렬된 다차원 배열의 모든 일치 배열입니다.
flags
다음 플래그의 조합일 수 있습니다(PREG_SET_ORDER와 함께 PREG_PATTERN_ORDER를 사용하는 것은 의미가 없음).
PREG_PATTERN_ORDER
$matches[0]이 전체 패턴 일치의 배열이고 $matches[1]이 첫 번째 괄호로 묶인 하위 패턴과 일치하는 문자열의 배열이 되도록 결과를 정렬합니다.
                           
<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=left>this is a test</div>",
    $out, PREG_PATTERN_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>
                           
                         

위의 예는 다음을 출력합니다.

<b>example: </b>, <div align=left>this is a test</div>
example: , this is a test
                         

따라서 $out[0]에는 전체 패턴과 일치하는 문자열 배열이 포함되고 $out[1]에는 태그로 묶인 문자열 배열이 포함됩니다.

패턴에 명명된 하위 패턴이 포함된 경우 $matches에는 하위 패턴 이름이 있는 키에 대한 항목이 추가로 포함됩니다.

패턴에 중복된 명명된 하위 패턴이 포함된 경우 맨 오른쪽 하위 패턴만 $matches[NAME]에 저장됩니다.

                           
<?php
preg_match_all(
    '/(?J)(?<match>foo)|(?<match>bar)/',
    'foo bar',
    $matches,
    PREG_PATTERN_ORDER
);
print_r($matches['match']);
?>
                           
                         

위의 예는 다음을 출력합니다.

Array
(
    [0] =>
    [1] => bar
)
                         
PREG_SET_ORDER
$matches[0]이 첫 번째 일치 집합의 배열이고 $matches[1]이 두 번째 일치 집합의 배열이 되도록 결과를 정렬합니다.
                           
<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=\"left\">this is a test</div>",
    $out, PREG_SET_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>
                           
                         

위의 예는 다음을 출력합니다.

<b>example: </b>, example:
<div align="left">this is a test</div>, this is a test
                         
PREG_OFFSET_CAPTURE
이 플래그가 전달되면 모든 일치 항목에 대해 추가 문자열 오프셋(바이트 단위)도 반환됩니다. 이것은 모든 요소가 오프셋 0에서 일치하는 문자열과 오프셋 1에서 subject에 대한 문자열 오프셋으로 구성된 배열인 배열의 배열로 matches 값을 변경합니다.
                           
<?php
preg_match_all('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
                           
                         

위의 예는 다음을 출력합니다.

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => foobarbaz
                    [1] => 0
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => foo
                    [1] => 0
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [0] => bar
                    [1] => 3
                )

        )

    [3] => Array
        (
            [0] => Array
                (
                    [0] => baz
                    [1] => 6
                )

        )

)
                         
PREG_UNMATCHED_AS_NULL
이 플래그가 전달되면 일치하지 않는 하위 패턴이 null로 보고됩니다. 그렇지 않으면 빈 문자열로 보고됩니다.

주문 플래그가 지정되지 않으면 PREG_PATTERN_ORDER가 가정됩니다.

offset
일반적으로 검색은 제목 문자열의 시작 부분에서 시작됩니다. 선택적 매개변수 offset을 사용하여 검색을 시작할 대체 위치(바이트 단위)를 지정할 수 있습니다.

메모: offset을 사용하는 것은 주제 문자열 대신 preg_match_all()substr($subject, $offset)을 전달하는 것과 같지 않습니다. pattern^, $ 또는 (?<=x)와 같은 주장을 포함할 수 있기 때문입니다. 예제는 preg_match()를 참조하십시오.


반환 값

전체 패턴 일치의 수(0일 수 있음)를 반환하거나 실패 시 false를 반환합니다.


오류/예외

전달된 정규식 패턴이 유효한 정규식으로 컴파일되지 않으면 E_WARNING이 발생합니다.


변경 로그

버전 설명
7.2.0 PREG_UNMATCHED_AS_NULL은 이제 $flags 매개변수에 대해 지원됩니다.

Examples

예제 #1 일부 텍스트에서 모든 전화번호를 가져옵니다.

                  
<?php
preg_match_all("/\(?  (\d{3})?  \)?  (?(1)  [\-\s] ) \d{3}-\d{4}/x",
                "Call 555-1212 or 1-800-555-1212", $phones);
?>
                  
                

예제 #2 일치하는 HTML 태그 찾기(greedy)

                  
<?php
// The \\2 is an example of backreferencing. This tells pcre that
// it must match the second set of parentheses in the regular expression
// itself, which would be the ([\w]+) in this case. The extra backslash is
// required because the string is in double quotes.
$html = "<b>bold text</b><a href=howdy.html>click me</a>";

preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER);

foreach ($matches as $val) {
    echo "matched: " . $val[0] . "\n";
    echo "part 1: " . $val[1] . "\n";
    echo "part 2: " . $val[2] . "\n";
    echo "part 3: " . $val[3] . "\n";
    echo "part 4: " . $val[4] . "\n\n";
}
?>
                  
                

위의 예는 다음을 출력합니다.

matched: <b>bold text</b>
part 1: <b>
part 2: b
part 3: bold text
part 4: </b>

matched: <a href=howdy.html>click me</a>
part 1: <a href=howdy.html>
part 2: a
part 3: click me
part 4: </a>
                

예제 #3 명명된 하위 패턴 사용

                  
<?php

$str = <<<FOO
a: 1
b: 2
c: 3
FOO;

preg_match_all('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);

/* Alternative */
// preg_match_all('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);

print_r($matches);

?>
                  
                

위의 예는 다음을 출력합니다.

Array
(
    [0] => Array
        (
            [0] => a: 1
            [1] => b: 2
            [2] => c: 3
        )

    [name] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [1] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [digit] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [2] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

)
                

기타