在HTML字符串的中间插入文本

时间:2012-05-08 12:16:32

标签: php regex string

在最近的句子之后/之前,HTML文本的中间部分被视为文本。

示例:

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

$middle = strlen($str) / 2;

我所做的是在.!?等所有停止字符上添加关键字,但仅限于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.<!-- stop --> Second sentence!<!-- stop --> <a title="Hello. 
World"> Third sentence.<!-- stop --> </a> Fourth sentence.<!-- stop --> Fifth
sentence?<!-- stop -->

现在,如何找到最接近<!-- stop -->位置的$middle子字符串,并在其前面插入我的文字?

有没有办法可以在preg_replace回调中找到$matches[1]相对于整个字符串的位置?这样我就可以将它与$ middle

进行比较

1 个答案:

答案 0 :(得分: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);
?>
这是怎么回事?