php
  • regex
  • function
  • 2013-05-28 3 views 4 likes 
    4

    문자열 내에서 단일 단어를 강조 표시하는 기능을 만들었습니다. 다음과 같이 보입니다 :RegEx를 사용하여 여러 단어 검색 및 일치

    function highlight($input, $keywords) { 
    
        preg_match_all('~[\w\'"-]+~', $keywords, $match); 
    
        if(!$match) { return $input; } 
    
        $result = '~\\b(' . implode('|', $match[0]) . ')\\b~i'; 
    
        return preg_replace($result, '<strong>$0</strong>', $input); 
    
    } 
    

    검색 할 때 공백을 지원하는 다른 단어의 배열을 사용하려면이 함수가 필요합니다.

    예 :

    function highlight($input, $keywords) { 
    
        foreach($keywords as $keyword) { 
    
         preg_match_all('~[\w\'"-]+~', $keyword, $match); 
    
         if(!$match) { return $input; } 
    
         $result = '~\\b(' . implode('|', $match[0]) . ')\\b~i'; 
    
         $output .= preg_replace($result, '<strong>$0</strong>', $keyword); 
    
        } 
    
        return $output; 
    
    } 
    

    :

    $search = array("this needs", "here", "can high-light the text");

    $string = "This needs to be in here so that the search variable can high-light the text";

    여기 echo highlight($string, $search);

    은 내가 그것을 필요가 어떻게 작동하는 기능을 수정하기 위해 지금까지 무슨이다 Obviou 교활한이 작동하지 않습니다 및이 작동하도록 (정규식 내 장점은 않습니다) 얻으려면 잘 모르겠습니다.

    문제가 될 수있는 다른 점은 함수가 여러 일치를 어떻게 처리할까요? 이러한 $search = array("in here", "here so"); 같은 결과는 같은 것 같이

    This needs to be <strong>in <strong>here</strong> so</strong> that the search variable can high-light the text

    을하지만이 있어야합니다 :

    This needs to be <strong>in here so</strong> that the search variable can high-light the text

    +0

    내가 잘못 될 수를 둘 중 하나이지만 $ 0 대신 $ 1이되어서는 안됩니까? – maiorano84

    +1

    나는 정말로 당신을 위해 대답하지 못했습니다. @ maiorano84하지만이 질문의 맨 위에있는 함수는 다음 구문을 사용하여 올바르게 작동한다고 말할 수 있습니다 :'echo highlight ("안녕하세요. 안녕하세요.", "morning hello");' –

    +1

    그런 다음 특정 부분이 정확할 가능성이 있습니다. 희망에 Upvote 당신은 당신의 대답을 얻을. – maiorano84

    답변

    3

    설명

    당신이 용어의 배열을 가지고 그들을 가입 할 수 정규식이나 문장을 사용하여 | 문자열로 중첩합니다. \b은 단어 조각을 포착하지 않도록 도와줍니다.

    \b(this needs|here|can high-light the text)\b

    enter image description here

    그런 다음 캡처 그룹 \1를 사용하여 대체이 실행

    ?

    내가 파이썬 실제 익숙하지 해요,하지만 PHP에서 나는 이런 식으로 뭔가 할 거라고 : 정규 표현식 나를 위해 강점 아니기 때문에

    <?php 
    $sourcestring="This needs to be in here so that the search variable can high-light the text"; 
    echo preg_replace('/\b(this needs|here|can high-light the text)\b/i','<strong>\1</strong>',$sourcestring); 
    ?> 
    
    $sourcestring after replacement: 
    <strong>This needs</strong> to be in <strong>here</strong> so that the search variable <strong>can high-light the text</strong> 
    
    +1

    위대한 답변과 내가 생각했던 것보다 훨씬 간단합니다! –

    +0

    친절한 단어 주셔서 감사합니다 :) –

    관련 문제