정규식(PCRE) preg_match
(PHP 4, PHP 5, PHP 7, PHP 8)
preg_match — 정규식 일치 수행
설명
preg_match( string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0 ): int|false
pattern
에 제공된 정규식과 일치하는 subject
을 검색합니다.
매개변수
pattern
- 문자열로 검색할 패턴입니다.
subject
- 입력 문자열입니다.
matches
matches
이 제공되면 검색 결과로 채워집니다. $matches[0]에는 전체 패턴과 일치하는 텍스트가 포함되고 $matches[1]에는 첫 번째 캡처된 괄호로 묶인 하위 패턴과 일치하는 텍스트가 포함됩니다.flags
flags
는 다음 플래그의 조합일 수 있습니다.PREG_OFFSET_CAPTURE
- 이 플래그가 전달되면 모든 일치 항목에 대해 추가 문자열 오프셋(바이트 단위)도 반환됩니다. 이것은 모든 요소가 오프셋
0
에서 일치하는 문자열과 오프셋1
에서subject
로의 문자열 오프셋으로 구성된 배열인 배열로matches
값을 변경합니다.<?php preg_match('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE); print_r($matches); ?>
위의 예는 다음을 출력합니다.
Array ( [0] => Array ( [0] => foobarbaz [1] => 0 ) [1] => Array ( [0] => foo [1] => 0 ) [2] => Array ( [0] => bar [1] => 3 ) [3] => Array ( [0] => baz [1] => 6 ) )
PREG_UNMATCHED_AS_NULL
- 이 플래그가 전달되면 일치하지 않는 하위 패턴이
null
로 보고됩니다. 그렇지 않으면 빈 문자열로 보고됩니다.<?php preg_match('/(a)(b)*(c)/', 'ac', $matches); var_dump($matches); preg_match('/(a)(b)*(c)/', 'ac', $matches, PREG_UNMATCHED_AS_NULL); var_dump($matches); ?>
위의 예는 다음을 출력합니다.
array(4) { [0]=> string(2) "ac" [1]=> string(1) "a" [2]=> string(0) "" [3]=> string(1) "c" } array(4) { [0]=> string(2) "ac" [1]=> string(1) "a" [2]=> NULL [3]=> string(1) "c" }
offset
- 일반적으로 검색은 제목 문자열의 시작 부분에서 시작됩니다. 선택적 매개변수
offset
을 사용하여 검색을 시작할 대체 위치(바이트 단위)를 지정할 수 있습니다.메모:offset
을 사용하는 것은 주제 문자열 대신 preg_match()에substr($subject, $offset)
을 전달하는 것과 같지 않습니다.pattern
이 ^, $ 또는 (?<=x)와 같은 주장을 포함할 수 있기 때문입니다.비교
<?php $subject = "abcdef"; $pattern = '/^def/'; preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3); print_r($matches); ?>
위의 예는 다음을 출력합니다.
Array ( )
while this example
<?php $subject = "abcdef"; $pattern = '/^def/'; preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE); print_r($matches); ?>
will produce
Array ( [0] => Array ( [0] => def [1] => 0 ) )
또는 substr()을 사용하지 않으려면
^
앵커 대신\G
어설션을 사용하거나 대신A
수정자를 사용하십시오. 둘 다offset
매개변수와 함께 작동합니다.
반환 값
preg_match()는 pattern
이 주어진 subject
와 일치하면 1을 반환하고 일치하지 않으면 0을 반환하고 실패하면 false
를 반환합니다.
경고 이 함수는 부울 false
을 반환할 수 있지만 false
으로 평가되는 부울이 아닌 값을 반환할 수도 있습니다. 자세한 내용은 부울 섹션을 참조하세요. 이 함수의 반환 값을 테스트하려면 === 연산자를 사용하십시오.
오류/예외
전달된 정규식 패턴이 유효한 정규식으로 컴파일되지 않으면 E_WARNING
이 발생합니다.
변경 로그
버전 | 설명 |
---|---|
7.2.0 | PREG_UNMATCHED_AS_NULL 은 이제 $flags 매개변수에 대해 지원됩니다. |
Examples
예제 #1 문자열 "php" 찾기
<?php
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>
예제 #2 "web"이라는 단어를 찾으십시오.
<?php
/* The \b in the pattern indicates a word boundary, so only the distinct
* word "web" is matched, and not a word partial like "webbing" or "cobweb" */
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>
예제 #3 URL에서 도메인 이름 가져오기
<?php
// get host name from URL
preg_match('@^(?:http://)?([^/]+)@i',
"http://www.php.net/index.html", $matches);
$host = $matches[1];
// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>
위의 예는 다음을 출력합니다.
domain name is: php.net
예제 #4 명명된 하위 패턴 사용
<?php
$str = 'foobar: 2008';
preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);
/* Alternative */
// preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);
print_r($matches);
?>
위의 예는 다음을 출력합니다.
Array ( [0] => foobar: 2008 [name] => foobar [1] => foobar [digit] => 2008 [2] => 2008 )
메모
팁 한 문자열이 다른 문자열에 포함되어 있는지 확인하려는 경우에만 preg_match()를 사용하지 마십시오. 대신 strpos()를 사용하면 더 빨라집니다.
기타
- PCRE Patterns
- preg_quote() - 정규 표현식 문자 인용
- preg_match_all() - 전역 정규식 일치 수행
- preg_replace() - 정규식 검색 및 바꾸기 수행
- preg_split() - 정규 표현식으로 문자열 분할
- preg_last_error() - 마지막 PCRE 정규식 실행의 오류 코드를 반환합니다.
- preg_last_error_msg() - 마지막 PCRE 정규식 실행의 오류 메시지를 반환합니다.