2014-07-18 5 views
-4

내에서 모든 일치를 교체합니다. 다음과 같이 시도하십시오 :태그 다음 줄이 있습니다

$pattern = '/(.*)(hello)(.*)(?=<\/)/ui'; 
$replacement = '$1<span style="background:yellow">$2</span>$3'; 

그러나 "hello"는 하나뿐입니다. 무엇을해야합니까?

+0

귀하의 HTML이 불균형합니다. ' zx81

+0

예를 들어, 다음으로 변경 했습니까? – HookeD74

+0

샘플에서 두 개의 헬리오가 div 안에 있지만 .hello 클래스는 찾을 수 없다고 기대할 수 있습니까? DomDocument (http : //php.net/manual/en/class.domdocument.php)를 사용하는 것이 더 나을 것입니다. – jrjohnson

답변

2

(* SKIP) (* F) 펄과 PCRE (PHP, 델파이, R ...) HTML을 구문 분석 할 정규식을 사용하는 방법에 대한 모든 권리 포기로

에서 구문, 우리는이 작업을 수행 할 수 있습니다 의외로 간단한 정규식 다음,478에서

$replaced = preg_replace('~<[^>]*>(*SKIP)(*F)|(hello)~i', 
         '<span style="background:yellow">$1</span>', 
         $yourstring); 

:

<[^>]*>(*SKIP)(*F)|(hello) 

샘플 PHP 코드, 하단의 대체 내용을 참조하십시오.

설명

이 문제는 기술의 고전적인 사례가 "regex-match a pattern, excluding..."

엔진에 건너 뜁니다 후 <tags> 다음 의도적으로 실패 | 일치 완료 교대의 왼쪽에이 질문에 설명되어 있습니다 캐릭터 라인의 다음의 위치 오른쪽에는 그룹 1-hello (대소 문자를 구분하지 캡처, 우리는 그들이 왼쪽의 표현식과 일치하지 않았기 때문에 그들이 올바른 사람 알고있다.

참조

+0

FYI : 데모 및 설명을 추가했습니다. :) – zx81

+0

대단히 감사합니다. – HookeD74

1

코드가 다소 까다 롭지 만 텍스트를 다른 요소에 줄 바꿈하는 것은 꽤 기본적인 작업입니다.

$html = <<<EOS 
<div class="hello"> Hello world &lt; hello world?! </div> 
EOS; 

$dom = new DOMDocument; 
$dom->loadHTML($html); 

$search = 'hello'; 

foreach ($dom->getElementsByTagName('div') as $element) { 
    foreach ($element->childNodes as $node) { // iterate all direct descendants 
     if ($node->nodeType == 3) { // and look for text nodes in particular 
      if (($pos = strpos($node->nodeValue, $search)) !== false) { 
       // we split the text up in: <prefix> match <postfix> 
       $postfix = substr($node->nodeValue, $pos + strlen($search)); 
       $node->nodeValue = substr($node->nodeValue, 0, $pos); 

       // insert <postfix> behind the current text node 
       $textNode = $dom->createTextNode($postfix); 
       if ($node->nextSibling) { 
        $node->parentNode->insertBefore($textNode, $node->nextSibling); 
       } else { 
        $node->parentNode->appendChild($textNode); 
       } 

       // wrap match in an element and insert it  
       $wrapNode = $dom->createElement('span', $search); 
       $element = $node->parentNode->insertBefore($wrapNode, $textNode); 
      } 
     } 
    } 
} 

echo $dom->saveHTML(), "\n"; 
관련 문제