2013-02-26 3 views
0

웹 페이지를 구문 분석하는 동안 내 파서가 잘못된 DOM 구조로 인해 중지됩니다. 특정 노드를 대체하여 문제를 해결하고 싶습니다.preg_replace 조건이 일치하는 경우

</div>이 있는데 파서가 중지되었습니다.

</div>이있는 경우 이있는 경우 </div> [즉, 다음을 검사 할 정규식을 작성해야합니다. 그 사이에 <div> 태그가 시작되지 않았습니다. 태그에 ID 또는 클래스가있을 수 있으므로 <div을 확인], 마지막 </div><div></div>으로 바뀝니다.

</div> 다음에 </div>이있는 경우 마지막 하나는 <div></div>으로 바뀝니다.

미리 감사드립니다.

예 : <div> <img src="/lexus-share/images/spacer.gif" width="2" height="15" border="0" alt=""> </div> <a href="http://www.somedomain.com"><img src="/pub-share/images.jpg"></a> </div>

+0

A : 시도와 코드를 입력하십시오. B : 정확하게 원하는 것을 명확히 할 수 있습니까? – christopher

+0

아마 그 질문에 편집 할 수 있습니다 :) – christopher

+0

그래서 그 모든 '

' has a '
'을 확인하고 싶습니다? – christopher

답변

0

이 단지 작품을 더 중첩 된 <div>들 (그들은 법적 확실하지 않은 경우)가없는 경우 :

$result = preg_replace(
    '%</div>  # Match a closing div tag 
    (    # Match and capture in group 1... 
    (?:   # ...the following regex: 
     (?!</?div>) # Match (unless a div tag intervenes) 
     .   # any character. 
    )*   # Repeat any number of times. 
    )    # End of capturing group 
    (?=</div>)  # Assert that a closing div tag follows%six', 
    '</div><div>\1', $subject); 

<div> <img src="/lexus-share/images/spacer.gif" width="2" height="15" border="0" alt=""> </div> <a href="http://www.somedomain.com"><img src="/pub-share/images.jpg"></a> </div> 

변경이

<div> <img src="/lexus-share/images/spacer.gif" width="2" height="15" border="0" alt=""> </div><div> <a href="http://www.somedomain.com"><img src="/pub-share/images.jpg"></a> </div> 
0

내가 제안하는 것은 정규식을 사용하는 것보다는 중첩 된 태그를 사용하는 것이 쉽지 않으므로 다른 접근 방식을 시도하는 것입니다.

난 당신이 문서를 구문 분석하는 데 사용하는 어떤 언어 모르겠지만, 당신이 쓸 수있는 코드의 논리는 다음과 같습니다

구문 분석 문자열 div> 검색 전체 문서를 통해 openingDivs을 계산하기 위해이 개 변수를 만들 및 닫는 Divs.

div> 앞에있는 문자가 < 일 경우, openingDivs ++입니다. div> 전에 문자 /, closingDivs ++ 및 조건이 적 진실하게되면 if (closingDivs > openingDivs)

을 확인을 경우

, 프로그램 출력을 사업부의 위치를하거나 공백 또는 널 (null)로 </div>를 교체 할 수 있습니다.

희망이 도움이됩니다. :)

관련 문제