2012-05-08 5 views
2

가장 가까운 문장 뒤 또는 앞에서 HTML 문자열의 중간 부분을 텍스트로 표시합니다.HTML 문자열 중간에 텍스트 삽입

예 :

$str = 'First sentence. Second sentence! <a title="Hello. World"> 
     Third sentence. </a> Fourth sentence. Fifth sentence?'; 
$str = preg_replace_callback("/(\.|\?|\!)(?!([^<]+)?>)/i", function($matches){ 
    return $matches[1].'<!-- stop -->'; 
}, $str); 

이 회전 : 내가 무슨 짓을했는지

$str = 'First sentence. Second sentence! <a title="Hello. World"> 
     Third sentence. </a> Fourth sentence. Fifth sentence?'; 

$middle = strlen($str)/2; 

는하지만 그들 외부 HTML 태그에, ., ! 또는 ? 같은 모든 중지 문자에 키워드를 추가하는 것입니다 $ str :

First sentence.<!-- stop --> Second sentence!<!-- stop --> <a title="Hello. 
World"> Third sentence.<!-- stop --> </a> Fourth sentence.<!-- stop --> Fifth 
sentence?<!-- stop --> 

이제 어떻게 할 수 있습니까? $middle 위치에 가장 가까운 하위 문자열이 <!-- stop -->이고 그 전에 텍스트를 삽입하고 있습니까?

전체 문자열에 상대적으로 내 preg_replace 콜백 내에 $matches[1]의 위치를 ​​찾을 수있는 방법이 있습니까? 그렇게하면 $ middle과 비교할 수 있습니다.

답변

4
<?php 
    $str = 'First sentence.<!-- stop --> Second sentence!<!-- stop --> <a title="Hello. 
    World"> Third sentence.<!-- stop --> </a> Fourth sentence.<!-- stop --> Fifth 
    sentence?<!-- stop -->'; 
    $str1 = explode('<!-- stop -->',$str); 
    $str1[round(sizeof($str1)/2)-2].="!Append text!"; 
    $glue=htmlentities('<!-- stop --/>'); 
    echo $str2 = implode($glue,$str1); 
?> 

이것은 어떻습니까?