2

被视为文本的 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位置的子字符串,并在它之前插入我的文本?

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

4

1 回答 1

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

这怎么样?

于 2012-05-08T12:25:38.730 回答