webbed webbed - 1 year ago 153
MySQL Question

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

I have a field

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

Answer Source

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']);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download