Page 1 of 1

replace h1 tag with h2 tag

Posted: Sun Apr 17, 2016 1:38 pm
by cjkeane
Hi everyone. I created an admin section where an admin user can modify aspects of the site (home page, about us, etc). This code retrieves 500 characters correctly, but I need to convert any h1-h6 to <h2>...</h2>.. Right now, the content is retrieved as it was saved in the db, and the h1-h6 do not changed to h2 as I was expecting. Can anyone provide some insight please?

Code: Select all

<?php  
	if (!$db) {die("Connection failed: " . mysqli_connect_error());	}
	$sql2="SELECT id,body FROM articles WHERE id=2";
	$result2=mysqli_query($db,$sql2);
	$row2 = mysqli_fetch_array($result2);
        if($row2) {$body2 = $row2['body']; }
	$aboutcontent = preg_replace('/<h[1-6]>(.*?)<\/h[1-6]>/', '<h2>$body2</h2>', $body2);
	echo substr($aboutcontent, 0, 500) . " ...";
?>

Re: replace h1 tag with h2 tag

Posted: Mon Apr 18, 2016 12:05 am
by requinix
Well, the regex doesn't account for capitalized <H#> tags, or that the heading could span multiple lines. But it would be easier to say what's wrong if we could see the $body2 that it isn't working with.

Also,
- The replacement regex is quite wrong. It'll replace every heading with literally "<h2>$body</h2>". Dollar sign and all. There are a couple issues with that, but they're moot because you should be replacing the heading with the contents of the heading: '<h2>$1</h2>'.
- The page will break horribly if you cut the string within a tag, like a <p>...</p> or <b>...</b>. If this is supposed to be a summary then I suggest removing all the HTML tags before getting the summary, which makes the whole "convert any h1-h6" thing irrelevant.

Re: replace h1 tag with h2 tag

Posted: Mon Apr 18, 2016 12:38 pm
by cjkeane
Thanks for your suggestions, however before receiving your response, I too decided it was best to simply remove all html. This actually made the text look better once all html was stripped out. :)