I have a HTML that is in various formats and I'm trying to standardize the code using PHP. In some cases I receive it using breaks
to separate lines. I need these to be <p>
tags instead.
1- For fist step I try to split the text by <br>
and add it to new holder
<?php
$text = 'I am <br><br> <br><p> <br>your firnd <br></p><p> </p> ok?';
$breaks = array("<br />","<br>","<br/>","<p>","</p>");
$text = str_ireplace($breaks, "<br>", $text);
echo "R1: ".htmlspecialchars($text, ENT_QUOTES, "UTF-8");
$text = explode("<br>", $text);
$newText = null;
for($i=0; $i < count($text) ;$i++)
{
if(!empty($text[$i]))
$newText .= "<p>".$text[$i]."</p>";
}
$breaks = array("<p></p>","<p> </p>","<p> </p>");
echo "<br/>R2: ".htmlspecialchars($newText, ENT_QUOTES, "UTF-8");
$newText = str_ireplace($breaks, "", $newText);
echo "<br/>R3: ".htmlspecialchars($newText, ENT_QUOTES, "UTF-8");
?>
Result:
R1: I am <br><br> <br><br> <br>your firnd <br><br><br> <br> ok?
R2: <p>I am </p><p> </p><p> </p><p>your firnd </p><p> </p><p> ok?</p>
R3: <p>I am </p><p> </p><p>your firnd </p><p> </p><p> ok?</p>
Do you a suggestion for me to improve this code? Also I have 2 issue whit that...
And how can avoid generate extra <p></p>
in my code and also how can remove attributes of p (id,class,meta,etc...) in p tag?
for example for this example:
$text = 'I am <br><br> <br><p id="ids" class="classes" meta-name="test"> <br>your firnd <br></p><p> </p> ok?';