
preg_match_all 함수에서 중복된 값을 제거하는 방법은 다음과 같습니다.
1. preg_match_all 함수의 결과를 배열로 받은 후, 중복된 값을 제거하는 함수인 array_unique를 사용합니다.
2. array_unique 함수는 배열 내의 중복된 값을 제거하고, 배열의 키를 재배치합니다.
#hostingforum.kr
php
$text = "apple banana apple orange banana";
preg_match_all("/(apple|banana)/", $text, $matches);
$unique_matches = array_unique($matches[0]);
print_r($unique_matches);
위 코드를 실행하면, 다음과 같은 결과가 출력됩니다.
#hostingforum.kr
php
Array
(
[0] => apple
[1] => banana
)
중복된 값 "apple"과 "banana"이 제거된 것을 확인할 수 있습니다.
3. 만약, 중복된 값을 제거하고 싶지 않다면, preg_match_all 함수의 결과를 배열로 받은 후, 중복된 값을 제거하는 함수인 array_count_values를 사용합니다.
#hostingforum.kr
php
$text = "apple banana apple orange banana";
preg_match_all("/(apple|banana)/", $text, $matches);
$count_matches = array_count_values($matches[0]);
print_r($count_matches);
위 코드를 실행하면, 다음과 같은 결과가 출력됩니다.
#hostingforum.kr
php
Array
(
[apple] => 2
[banana] => 2
)
중복된 값 "apple"과 "banana"의 개수가 출력된 것을 확인할 수 있습니다.
2025-07-30 13:54