Strip Tags PHP

Stripping HTML Tags From Database Output

When you output data from a mysql database, the text could be html code with various tags such as <p>, <div> and span. Therefore, if you just selected the text for output you could end up with undesired output.

Now, let's assume that you want to convert the html into plain text just as though it was interpreted from a browser. What you need to do is remove the whitespace and html tags and display the words you want to see. With PHP you can use the clever strip_tags() function to remove the html tags and use the trim() function to remove whitespace. The code below shows how to remove all html tags from a database entry.

$command = "select text from mytable ";
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc) {
$myhtml = $row['text'];
$myhtml= substr($myhtml, 0, 100);
$myhtml = strip_tags($myhtml, '');//strips all tags

echo '<p>'.$row[text].'<br /><br/>
</p>';

}

The code below shows how to remove all html tags from a database entry except the <p> tag.

$command = "select text from mytable ";
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc) {
$myhtml = $row['text'];
$myhtml = trim(strip_tags($myhtml, '<p>')); //Leaves the <p> tag but removes all other html tags
$myhtml= substr($myhtml, 0, 80); //takes only the first 80 characters of the string

echo '<p>'.$row[text].'<br /><br/>
</p>';
}