가능한 중복 : 나는 HTML 또는 순수 텍스트 문자열에 검색어를 강조 아이디어로 어려움을 겪고있다
Highlight keywords in a paragraph정규식 하이라이트 검색어
. 나는 여기에서 작동하지 않는 많은 예제를 보았습니다. 여기에 나의 균열이 있습니다. 이것이 html을 깨뜨릴 수도 있고 작동하지 않을 몇몇 사례를 제공해주십시오. 내가 생각해 낼 수있는 유일한 두 가지 경우는 : "나는 컴퓨터보다"이고 형식이 잘못된 html과 같은 텍스트 문자열 내에>가있는 경우입니다. 여기 코드가 있습니다. 당신을 감사하고 나는 내가이의 DOMDocument 클래스를 사용하고, 단순히 일반 텍스트 대신 닌자 정규식을 마련하기 위해 노력하는 노드의 내용을 대체 할 것입니다 누군가에게
function search_highlight($text,$search_terms)
{
$color = array('#FFFF00','#00FFFF','#FF9900','#00FF00','#CCCCCC','red','grean','orange');
$count = 0;
if (! is_array($search_terms))
{
$search_terms = explode(' ', $search_terms);
}
// Highlight each of the terms
foreach ($search_terms as $term)
{
//skip blank terms that arise from double spaces
if(! $term) continue;
//Regex Explained:
//The regex first matches a word boundary
//Next it matches the search term liternal
//Next it matches a word boundary
//Next is matches, but doesn't include the following regex...
//Anything other than the literals <and> zero or more times
//Next it will match either a < literal or the end of the string
$text = preg_replace('/\b('.preg_quote(trim($term)).')\b(?=[^><]*<|.$)/i', '<span style="background-color:'.$color[$count].'">\1</span>', $text);
//increment counter for new color
$count++;
}
return $text;
}
그들 모두가 아마 일을하지 않는 이유는 Regex가 아닌 DOM을 사용하기 때문입니다. – Gordon
DOM을 통과하기 위해 javascript를 사용합니까? 그렇다면 당신이 제안 할 플러그인이 있습니까? 나는 단지 하나의 PHP DOM 파서를 보았고 아주 느리다. – John
javascript 또는 http://php.net/dom – Gordon