Replace tags stored in database keeping the string between them

For example, if I have

<b>some king of #1 Text</b>

stored in a mysql table, is there a way to change it to

<h2>some king of #1 Text</h2>

without going to each row and manually changing it.?

In some cases [if possible] I need to replace

<p><b>some king of #1 Text</b></p><p>other text</p>

with

<h2>some king of #1 Text</h2><p>other text</p>

. I was thinking maybe sql expressions.

Answers


Use the REPLACE() function if your tags only look like <b> and </b> without other attributes, since this really just amounts to a simple string replacement action.

UPDATE yourtable SET thecolumn = REPLACE(thecolumn, '<b>', '<h2>');
UPDATE yourtable SET thecolumn = REPLACE(thecolumn, '</b>', '</h2>');

If your tags contain other attributes like <b class='something'> you are best off just to modify it at the time of output using an HTML parser.

Update after question was edited:

If you have the exact pattern <p><b>...</b></p> without extra whitespace, you can still use REPLACE(), but you will need to run this pair before the two listed above.

UPDATE yourtable SET thecolumn = REPLACE(thecolumn, '<p><b>', '<h2>');
UPDATE yourtable SET thecolumn = REPLACE(thecolumn, '</b></p>', '</h2>');

Anything beyond this in complexity will best be handled by modifying the HTML in application code with a proper HTML parser as I mentioned before.


Need Your Help