Jump to content

[SOLVED] preg_replace from a database


gerkintrigg

Recommended Posts

Hi.

If I want to replace words in a string, but ignore the HTML I use:

$word='you';

$pattern = "~\b".$word."\b(?![^<]*?>)~i"; 

$new_word='<span class="flagged" onClick="alert(\''.$r['word'].' needs replacing with a better one\');">'.$r['word'].'</span>';
	$page = preg_replace($pattern, $new_word, $page);

 

The code then ignores HTML, which is perfect, but how do I do this from a database?

 

I have tried all the standard stuff of separating the $r['word']; variable out and referencing it into a string like this:

$word=$r['word'];

 

but it offers this error:

Warning: preg_replace() [function.preg-replace]: Compilation failed: nothing to repeat at offset 2 in /[path to PHP file] on line 104

 

line 104 is:

$page = preg_replace($pattern, $new_word, $page);

 

Any ideas why it's playing up?

Link to comment
Share on other sites

It kinda amazes me how you failed to post the contents of $r['word'] when you get the error. But aside from that, my guess is that it contains special regex characters. Either way, you should simply use preg_quote() to escape any characters with special meaning:

 

$word = preg_quote($r['word'], '~');

Link to comment
Share on other sites

And instead of using $r['word'] in the replacement string, you can use $0, which will be replaced by the pattern match. That way the casing of the word will always remain the same.

 

$new_word = '<span class="flagged" onClick="alert(\'$0 needs replacing with a better one\');">$0</span>';

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.