PHP 버전
4+
/* 문자열에서
   모든 일치하는 정규 표현식 패턴의 문자열을 찾아서
   그 개수를 정수로 반환합니다. */

// 주어진 문자열
$str = 'apple orange banana apple';

// 검색할 정규 표현식 패턴
$pattern = '/apple/';

// 함수에 적용 및 결과 반환
$result = preg_match_all($pattern, $str);
var_dump($result); // 출력: int(2)

/* 일치하는 모든 부분 문자열을
   각각의 요소들로 구성된 배열로도 저장할 수 있습니다.
   세 번째 매개변수에 할당할 변수를 지정하면 됩니다. */

// 세 번째 매개변수에 할당할 변수($matches) 지정
$result = preg_match_all($pattern, $str, $matches);

// 할당된 배열 확인
print_r($matches);
/* 출력:
Array
(
    [0] => Array
        (
            [0] => apple
            [1] => apple
        )

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

/* preg_match_all(
	패턴,
	검색 대상이 되는 문자열[,
	일치하는 부분을 저장할 배열[, 
	추가적인 설정을 지정하는 플래그[, 
	검색을 시작할 문자열 내의 오프셋]]]
);
*/
$pattern = '/apple/';
$subject = "apple orange banana apple";

$result = preg_match_all($pattern, $subject);

if ($result !== false) {
    var_dump($result); // 출력: int(2)
}
$pattern = '/grape/';
$subject = "apple orange banana apple";

$result = preg_match_all($pattern, $subject);

if ($result !== false) {
    var_dump($result); // 출력: int(0)
}
error_reporting(0); // 에러 표시 비활성화

$pattern = '/apple'; // 유효하지 않은 정규 표현식을 사용
$subject = "apple orange banana apple";

$result = preg_match_all($pattern, $subject);

if ($result !== false) {
    var_dump($result);
} else {
	 echo '에러가 발생했습니다.';
}

// 출력: '에러가 발생했습니다.'
// 주어진 문자열에서 숫자 찾기
$string = '이것은 123과 456을 포함한 샘플 텍스트입니다.';

// 패턴: 숫자 찾기
$pattern = '/\d+/';

// $matches라는 빈 배열을 선언하여 할당할 공간을 마련합니다.
$matches = array();

// $matches를 매개변수에 할당합니다.
$num_of_matches = preg_match_all($pattern, $string, $matches);

// 결과 출력
if ($num_of_matches > 0) {
	var_dump($matches); // array(1) { [0]=> array(2) { [0]=> string(3) "123" [1]=> string(3) "456" } }
}
// 예제 문자열
$string = "apple orange banana apple";

// 정규식 패턴: 'apple' 또는 'orange'를 찾고 괄호 그룹으로 묶음
$pattern = '/(apple|orange)/';

// PREG_PATTERN_ORDER 사용
// - 매칭 결과를 패턴(캡처 그룹) 기준으로 정렬
// - $matches    : 결과를 할당할 배열 변수
// - $matches[0] : 전체 패턴에 일치한 문자열들
// - $matches[1] : 첫 번째 괄호 그룹에 일치한 문자열들
preg_match_all($pattern, $string, $matches, PREG_PATTERN_ORDER);

// 결과 출력
print_r($matches);

/*
출력:
Array
(
    [0] => Array ( [0] => apple [1] => orange [2] => apple )
    [1] => Array ( [0] => apple [1] => orange [2] => apple )
)
*/
// 예제 문자열
$string = "apple orange banana apple";

// 정규식 패턴: 'apple' 또는 'orange'를 찾고 괄호 그룹으로 묶음
$pattern = '/(apple|orange)/';

// PREG_SET_ORDER 사용
// - 매칭된 결과를 한 번의 매칭 단위로 묶어 정렬
// - $matches                    : 결과를 할당할 배열 변수
// - $matches[0], $matches[1], … : 각각 한 번의 매칭 결과
preg_match_all($pattern, $string, $matches, PREG_SET_ORDER);

// 결과 출력
print_r($matches);

/*
출력:
Array
(
    [0] => Array ( [0] => apple [1] => apple )   // 첫 번째 매칭: 전체 + 첫 번째 그룹
    [1] => Array ( [0] => orange [1] => orange ) // 두 번째 매칭: 전체 + 첫 번째 그룹
    [2] => Array ( [0] => apple [1] => apple )   // 세 번째 매칭: 전체 + 첫 번째 그룹
)
*/
// 예제 문자열
$string = "apple orange banana apple";

// 정규식 패턴: 'apple' 또는 'orange'를 찾고 괄호 그룹으로 묶음
$pattern = '/(apple|orange)/';

// PREG_OFFSET_CAPTURE 사용
// - 각 매칭 결과에 문자열의 시작 위치(offset)를 함께 저장
// - $matches : 결과를 할당할 배열 변수
// - $matches의 각 요소는 [일치한 문자열, 시작 위치 인덱스] 형태
preg_match_all($pattern, $string, $matches, PREG_OFFSET_CAPTURE);

// 결과 출력
print_r($matches);

/*
출력:
Array
(
    [0] => Array ( 
        [0] => Array("apple", 0)    // 전체 패턴 첫 번째 매칭과 위치
        [1] => Array("orange", 6)   // 전체 패턴 두 번째 매칭과 위치
        [2] => Array("apple", 19)   // 전체 패턴 세 번째 매칭과 위치
    )
    [1] => Array ( 
        [0] => Array("apple", 0)    // 첫 번째 그룹 첫 번째 매칭과 위치
        [1] => Array("orange", 6)   // 첫 번째 그룹 두 번째 매칭과 위치
        [2] => Array("apple", 19)   // 첫 번째 그룹 세 번째 매칭과 위치
    )
)
*/
// 예제 문자열
$string = "apple banana";

// 정규식 패턴: 'apple', 'banana', 'orange' 세 그룹
$pattern = '/(apple)|(banana)|(orange)/';

// PREG_UNMATCHED_AS_NULL 사용
// - 일치하지 않은 하위 패턴(subpattern)을 null로 처리
// - $matches : 결과를 할당할 배열 변수
// - $matches[0], $matches[1], ... 각 그룹의 매칭이 null 또는 문자열로 저장
preg_match_all($pattern, $string, $matches, PREG_PATTERN_ORDER | PREG_UNMATCHED_AS_NULL);

// 결과 출력
print_r($matches);

/*
출력:
Array
(
    [0] => Array ( [0] => apple [1] => banana )   // 전체 패턴 매칭
    [1] => Array ( [0] => apple [1] => null )     // 첫 번째 그룹: 'apple'만 매칭
    [2] => Array ( [0] => null [1] => banana )    // 두 번째 그룹: 'banana'만 매칭
    [3] => Array ( [0] => null [1] => null )      // 세 번째 그룹: 'orange' 매칭 없음 → null
)
*/
$string = '문의는 help@example.com 또는 support@example.org 으로 연락 주시기 바랍니다.';
$pattern = '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/';
$matches = array();

$result = preg_match_all($pattern, $string, $matches);

if ($result !== false && $result > 0) {
    print_r($matches[0]);       // 모든 매칭 이메일 출력
    echo "\n첫 번째 이메일: " . $matches[0][0]; // 첫 번째 이메일만 출력
} else {
    echo '이메일 주소 형식이 없습니다.';
}

// 출력:
// Array ( [0] => help@example.com [1] => support@example.org )
// 첫 번째 이메일: 'help@example.com'
$string = '더 많은 정보는 https://www.example.com에서 확인하세요.';
$pattern = '/\b(?:https?:\/\/)?(?:www\.)?[a-zA-Z0-9-]+(?:\.[a-z]{2,})+(?:\/[^\s]*)?\b/';
$matches = array();

$result = preg_match_all($pattern, $string, $matches);

if ($result !== false && $result > 0) {
    echo $matches[0][0]; // 첫 번째 매칭 URL 출력
} else {
    echo 'URL 형식이 없습니다.';
}

// 출력: 'https://www.example.com'
$html = '<div class="container"><p>Hello, <b>world!</b></p></div>';
$tagPattern = '/<[^>]+>/';  // HTML 태그를 찾는 정규식
$matches = array();

$result = preg_match_all($tagPattern, $html, $matches);

if ($result !== false && $result > 0) {
    print_r($matches[0]);  // 모든 매칭 태그 출력
} else {
    echo '태그를 찾지 못했습니다.';
}

// 출력:
// Array ( [0] => <div class="container"> [1] => <p> [2] => <b> [3] => </b> [4] => </p> [5] => </div> )
$css = '.header { color: #333; } .main-content { font-size: 16px; }';
$classPattern = '/\.([a-zA-Z0-9_-]+)/'; // CSS 클래스 선택자 패턴
$matches = array();

$result = preg_match_all($classPattern, $css, $matches);

if ($result !== false && $result > 0) {
    print_r($matches[0]);  // 매칭된 클래스 선택자 전체 출력
} else {
    echo 'CSS 클래스 선택자를 찾지 못했습니다.';
}

// 출력:
// Array ( [0] => .header [1] => .main-content )