webbed webbed - 4 months ago 38
MySQL Question

How to remove html tags except <br> from mysql data?

I have a field

Product_description
in mysql table, which has html tags. I want to update this field with removing html tags except
br
. I know I can do this with
strip_tag
but I don't understand how to accomplish this for the table data.

Answer

To remove all tags but <br> from a text, you can indeed use strip_tags:

$var = strip_tags($html, '<br>');

See an example here.

From the docs:

You can use the optional second parameter to specify tags which should not be stripped.



Since you want to change the persisted data (not to run the script everytime), you can create a heavy running script to be used once and update the values. Like this: (You might want to use trim too)

$con = new mysqli('localhost', 'username', 'password', 'database_name');
$stmt = $con->query('SELECT * FROM table_name');
while($row = $stmt->fetch_assoc()){
    $stmt2 = $con->prepare('UPDATE table_name set Product_description = ? WHERE Product_id = ?');
    $tmp = strip_tags($row['Product_description'], '<br>');
    $stmt2->bind_param("si", $tmp, $row['Product_id']);
    $stmt2->execute();
}

That script would be for you to run it just once, so it's (arguably) ok if it's slow...