
preg_match_all 함수는 PHP에서 사용하는 정규표현식 함수 중 하나로, 문자열 내의 모든 패턴을 찾는 함수입니다.
중복된 값을 제거하고 싶다면, preg_match_all 함수의 결과를 배열로 받은 후, 중복된 값을 제거하는 함수인 array_unique를 사용하면 됩니다.
예를 들어, 다음과 같이 사용할 수 있습니다.
#hostingforum.kr
php
$string = "hello hello hello world";
$pattern = "/hello/";
preg_match_all($pattern, $string, $matches);
$uniqueMatches = array_unique($matches[0]);
print_r($uniqueMatches);
이 코드를 실행하면, $uniqueMatches 배열의 내용은 다음과 같습니다.
#hostingforum.kr
php
Array
(
[0] => hello
[1] => hello
)
이러한 결과가 나온 이유는 array_unique 함수는 배열의 중복된 값을 제거하는 함수이기 때문입니다.
만약, 중복된 값을 제거하고 싶지 않다면, preg_match_all 함수의 결과를 그대로 사용하면 됩니다.
#hostingforum.kr
php
$string = "hello hello hello world";
$pattern = "/hello/";
preg_match_all($pattern, $string, $matches);
print_r($matches[0]);
이 코드를 실행하면, $matches[0] 배열의 내용은 다음과 같습니다.
#hostingforum.kr
php
Array
(
[0] => hello
[1] => hello
[2] => hello
)
이러한 결과가 나온 이유는 preg_match_all 함수가 모든 패턴을 찾기 때문입니다.
이러한 예제를 통해 preg_match_all 함수와 array_unique 함수를 사용하여 중복된 값을 제거하는 방법을 이해할 수 있습니다.
2025-06-04 03:09