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


Insert text in the middle of a HTML 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 -->

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

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

<?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);
?>

这是怎么回事?