문자열 내에서 단일 단어를 강조 표시하는 기능을 만들었습니다. 다음과 같이 보입니다 :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 대신 $ 1이되어서는 안됩니까? – maiorano84
나는 정말로 당신을 위해 대답하지 못했습니다. @ maiorano84하지만이 질문의 맨 위에있는 함수는 다음 구문을 사용하여 올바르게 작동한다고 말할 수 있습니다 :'echo highlight ("안녕하세요. 안녕하세요.", "morning hello");' –
그런 다음 특정 부분이 정확할 가능성이 있습니다. 희망에 Upvote 당신은 당신의 대답을 얻을. – maiorano84