I want to format multiple paragraphs to a better html structure
There is a database with a column called bodytext $bodytext = $row["bodytext"];
If i echo this you get multiple paragraphs
This is one paragraph:
— START paragraph 1
<b>lorem</b> description 1 <b>lorem</b> description 2 <b>lorem</b> description 3 <b>lorem</b> description 4 <b>lorem</b> description 5 <b>lorem</b> description 6
— END paragraph 1
The final result for one example paragraph:
— START paragraph 1
<h1>lorem</h1> decription 1 <h2>lorem</h2> description 2 <h2>lorem</h2> description 3 <h3>lorem</h3> description 4 <h3>lorem</h3> description 5 <h3>lorem</h3> description 6
— END paragraph 1
I want to format the b tags into hierachical header tags from h1 to h4 That means h1 can be exists only once, h2 only 2 times, h3 times, h4 for all the rest The number of headers with text depends on the content, another paragraph can have only three headers with text…
What is the best way for php?
Advertisement
Answer
If your content is formed as your example shows you can use this:
$text = ''; // your example text goes here $i = 1; $matches = null; while (true) { $text = preg_replace('|<(/)?b>|', ('<1h'.$i.'>'), $text, 2, $matches); if (!$matches) { break; } if ($i < 4) $i++; $matches = null; }
You can see this work here: