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
https://forums.phpfreaks.com/topic/181662-solved-preg_replace-from-a-database/
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'], '~');

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.