I wrote a code which is changing headings h1 to h2 if it's not first heading of that type. It works, but only when I'm using just PHP. If I want to use it on website, which one is using database to output content, that code doesn't work.
I'm using ob_start() before <html>
and ob_get_contents() + ob_end_clean() + rest of my code after </html>
, so I think that has to be something wrong "catching" content from database, but I'm not sure. I tried to use that code on a website based on WordPress.
My code (I know it isn't probably the best solution, but it works when I'm using it on any website without CMS):
<!DOCTYPE html>
<?php
ob_start();
?>
<html>
<head>
<title>random page</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-5">
<h1>afdsfdassfdfdsa</h1>
</div>
</div>
</div>
<h1>sadffsadf afdsfdsa afsdfs?</h1>
<h1 class="superclass">random text?</h1>
<div>
<p>some ending content</p>
</div>
</body>
</html>
<?php
$bufferContent = ob_get_contents();
ob_end_clean();
$matchedContent = '';
$endContent = '';
$modifiedContent = '';
$firstHeadingBoolean = true;
$h1Pattern = array();
$h1Pattern[0] = '%<h1(.*?)>%';
$h1Pattern[1] = '%</h1>%';
$h1Replacement = array();
$h1Replacement[0] = '<h2$1>';
$h1Replacement[1] = '</h2>';
if(preg_match_all('%((.|\n)*?)(<h1.*?>.*?</h1>)%', $bufferContent, $contentMatches)){
foreach($contentMatches[0] as $matches) {
$matchedContent .= $matches;
}
$endContent = str_replace($matchedContent, '', $bufferContent);
foreach ($contentMatches[0] as $matches) {
if(!$firstHeadingBoolean){
$firstHeadingBoolean = false;
} else {
$matches = preg_replace($h1Pattern, $h1Replacement, $matches);
}
$modifiedContent .= $matches;
}
echo $modifiedContent;
echo $endContent;
} else {
echo $bufferContent;
}
?>
EDIT: I tried to use solutions from there but nothing has changed: WordPress filter to modify final html output Now, after some testing, I can see it's not working because preg_match_all doesn't work correctly. Anyone has an idea what is wrong with that preg_match_all? I tested that regex pattern inside that in regex101 and on my localhost and everything worked fine. I don't understand, why isn't it working here?