1

I'm trying to perform a find and replace (actually, a delete) on a particular column in a MySQL database (circa 20k+ records) where the column in question contains HTML (the body text for page content in a CMS).

I need to find and replace/delete the following text from within each record and leave all of the other HTML intact (the below string appears only once per record):

<h2>Location Map</h2><p><a href="[?]" onclick="window.open(this.href); return false;">[?]</a></p>

Where "[?]" is a string of variable content and length (both alphanumeric and symbols) and the rest static content exactly as it's shown above.

I know this should be very simple and a bit of a stupid question but I'm no regular expression expert and can't quite work out what I'm doing wrong (possible not escaping enough characters or too many).

Preferably I'd like a regex I can use in phpMyAdmin to perform the find and replace.

Many thanks in advance.

1
  • MariaDB has REGEXP_REPLACE, MySQL does not. Commented Mar 22, 2016 at 23:35

1 Answer 1

1

The find/replace statement in PHP could be something like this:

$regex = '#<h2>Location Map</h2><p><a href="(.*?)" onclick="window.open.*?>(.*?)</a></p>#';
$result = preg_replace($regex, $replace, $html);

...where $html would be the original data you retrieve from your database, and $replace the value you want to insert instead of the matched string.

For instance, if:

$html = 'all that comes before
<h2>Location Map</h2><p><a href="http://www.foofle.com" onclick="window.open(this.href); return false;">Foofle</a></p>
all that comes after';

$replace = "(link=$1, text=$2)";

$result = preg_replace($regex, $replace, $html);
echo $result;

Outputs:

all that comes before
(link=http://www.foofle.com, text=Foofle)
all that comes after

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.