My string is an HTML document. I want to add a dot before HTML closing tags when there is not punctuation right before. Punctuation is .,?!: and I want to use preg_replace for that.
<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>
My function:
$source = 'the above html';
$source = addMissingPunctuation( $source );
echo $source;
function addMissingPunctuation( $input ) {
$tags = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ];
foreach ($tags as $tag) {
$input = preg_replace(
"/[^,.;!?](<\/".$tag.">)/mi",
".${0}",
$input
);
}
return $input;
}
I tried .${0},.$0, .${1},.$1, .\\0,.\\1 but nothing works. At best, it swallows the match but doesn't replace it with anything. The matching part of my pattern seems to work on regex101 and other sites.
Desired result is:
<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>