
preg_match_all 함수는 패턴 매칭 결과를 배열로 반환합니다. 이 배열에는 중복된 값이 포함될 수 있습니다.
이유는 preg_match_all 함수가 패턴 매칭 결과를 배열로 반환할 때, 중복된 값을 제거하지 않는다는 것입니다.
예를 들어, 다음 패턴이 주어졌을 때, "hello"가 두 번 반복되는 경우, 결과에서 중복된 값이 제거되지 않습니다.
#hostingforum.kr
php
$pattern = '/hello/';
$text = 'hellohello';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);
이 코드를 실행하면, 다음 결과가 출력됩니다.
#hostingforum.kr
php
Array
(
[0] => hello
[1] => hello
)
위의 결과에서, 중복된 값 "hello"가 제거되지 않았습니다.
이러한 결과를 얻으려면, 중복된 값을 제거하기 위해 preg_match_all 함수의 옵션을 사용할 수 있습니다.
예를 들어, 다음 코드를 사용할 수 있습니다.
#hostingforum.kr
php
$pattern = '/hello/';
$text = 'hellohello';
preg_match_all($pattern, $text, $matches, PREG_SET_ORDER);
print_r($matches);
이 코드를 실행하면, 다음 결과가 출력됩니다.
#hostingforum.kr
php
Array
(
[0] => Array
(
[0] => hello
)
[1] => Array
(
[0] => hello
)
)
위의 결과에서, 중복된 값 "hello"가 제거되었습니다.
또한, preg_match_all 함수의 옵션 중 하나인 PREG_OFFSET_CAPTURE 옵션을 사용할 수 있습니다.
예를 들어, 다음 코드를 사용할 수 있습니다.
#hostingforum.kr
php
$pattern = '/hello/';
$text = 'hellohello';
preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
이 코드를 실행하면, 다음 결과가 출력됩니다.
#hostingforum.kr
php
Array
(
[0] => Array
(
[0] => hello
[1] => 0
)
[1] => Array
(
[0] => hello
[1] => 6
)
)
위의 결과에서, 중복된 값 "hello"가 제거되었습니다.
이러한 옵션을 사용하여, 중복된 값을 제거할 수 있습니다.
2025-05-18 17:39