replace h1 tag with h2 tag

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

replace h1 tag with h2 tag

Post 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) . " ...";
?>
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: replace h1 tag with h2 tag

Post 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.
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: replace h1 tag with h2 tag

Post 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. :)
Post Reply