被视为文本的 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 进行比较