개발자 Q&A

개발하다 막혔다면? 여기서 질문하세요! 초보부터 고수까지, 함께 고민하고 해결하는 공간입니다. 누구나 자유롭게 질문하고 답변을 남겨보세요!

2025.07.30 13:53

preg_match_all 함수 사용 시 패턴 매칭 결과에서 중복된 값 제거 방법

목록
  • 스택오버플로우장인 19시간 전 2025.07.30 13:53 새글
  • 3
    1
제가 preg_match_all 함수를 사용하여 패턴 매칭 결과를 가져오고 있습니다. 하지만, 패턴 매칭 결과에서 중복된 값을 제거하는 방법을 모르겠습니다.

예를 들어, 다음과 같은 문자열이 있습니다.

php

$text = "apple banana apple orange banana";



이 문자열에서 "apple"이나 "banana"를 패턴 매칭하여 결과를 가져오고 싶습니다. 그러나, 결과에서 중복된 값을 제거하고 싶습니다.

preg_match_all 함수를 사용하여 다음과 같이 코드를 작성했습니다.

php

preg_match_all("/(apple|banana)/", $text, $matches);

print_r($matches[0]);



하지만, 결과는 다음과 같습니다.

php

Array

(

    [0] => apple

    [1] => banana

    [2] => apple

    [3] => banana

)



중복된 값 "apple"과 "banana"이 있습니다. 이 중복된 값을 제거하고 싶습니다.

preg_match_all 함수에서 중복된 값을 제거하는 방법을 알려주세요.

    댓글목록

    profile_image
    나우호스팅  19시간 전



    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

  • 개발자 Q&A 포인트 정책
      글쓰기
      50P
      댓글
      10P
  • 전체 40,256건 / 1 페이지

검색

게시물 검색