Php 在结束HTML标记之前添加缺少的标点

Php 在结束HTML标记之前添加缺少的标点,php,html,regex,preg-replace,regex-group,Php,Html,Regex,Preg Replace,Regex Group,我的字符串是一个HTML文档。当前面没有标点符号时,我想在HTML结束标记之前添加一个点。标点符号是,!:我想用preg\u replace来解决这个问题 <p>Today, not only we have so many breeds that are trained this and that.</p> <h4><strong>We must add a dot after the closing strong</strong>

我的字符串是一个HTML文档。当前面没有标点符号时,我想在HTML结束标记之前添加一个点。标点符号是
,!:
我想用
preg\u replace
来解决这个问题

<p>Today, not only we have so many breeds that are trained this and that.</p>

<h4><strong>We must add a dot after the closing strong</strong></h4>

<p>Hunting with your dog is a blah blah with each other.</p>

<h2>No need to change this one!</h2>

<p>Hunting with your dog is a blah blah with each other.</p>

您不需要像这样迭代
$tags
,我要么使用
|
执行
内爆
,要么在本例中为所有可能的元素创建一个正确的规则

$source = '<p>Today, not only we have so many breeds that are trained this and that.</p>

<h4><strong>We must add a dot after the closing strong</strong></h4>

<p>Hunting with your dog is a blah blah with each other.</p>

<h2>No need to change this one!</h2>

<p>Hunting with your dog is a blah blah with each other.</p>';
$source = addMissingPunctuation( $source );
echo $source;
function addMissingPunctuation( $input ) {
    return preg_replace("/[^,.;!?]\K<\/h[1-6]>/mi", ".$0", $input);
}
你也可以改变你的想法;不过,这更符合个人偏好。如果您不介意转义
/
的话,您可以继续这样做,如果不只是用
~
交换开头和结尾的
/

演示:

preg\u replace(“~[^,.;!?]\K~mi”

it work chris,将对其进行剖析以了解原因…非常感谢,我挠头了一段时间…如果你将其作为答案,我可以将其标记为解决方案这是一个很好的解决方案chris。我觉得缺少的唯一一点是建议将模式分隔符更改为
~
或其他东西,以便在模式内向前斜线不必逃避。否则,你就把我挤出了这一页——我没有什么有价值的东西可以发布!我想听听你对我的一个问题的看法。请加入我的行列:
<p>Today, not only we have so many breeds that are trained this and that.</p>

<h4><strong>We must add a dot after the closing strong</strong>.</h4>

<p>Hunting with your dog is a blah blah with each other.</p>

<h2>No need to change this one!</h2>

<p>Hunting with your dog is a blah blah with each other.</p>
$source = '<p>Today, not only we have so many breeds that are trained this and that.</p>

<h4><strong>We must add a dot after the closing strong</strong></h4>

<p>Hunting with your dog is a blah blah with each other.</p>

<h2>No need to change this one!</h2>

<p>Hunting with your dog is a blah blah with each other.</p>';
$source = addMissingPunctuation( $source );
echo $source;
function addMissingPunctuation( $input ) {
    return preg_replace("/[^,.;!?]\K<\/h[1-6]>/mi", ".$0", $input);
}
[,.;!?]<\/h[1-6]>(*SKIP)(*FAIL)|<\/h[1-6]>
preg_replace("~[^,.;!?]\K</h[1-6]>~mi"