gerkintrigg Posted November 15, 2009 Share Posted November 15, 2009 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? Quote Link to comment https://forums.phpfreaks.com/topic/181662-solved-preg_replace-from-a-database/ Share on other sites More sharing options...
gerkintrigg Posted November 16, 2009 Author Share Posted November 16, 2009 I get an error: Compilation failed: nothing to repeat at offset Quote Link to comment https://forums.phpfreaks.com/topic/181662-solved-preg_replace-from-a-database/#findComment-958767 Share on other sites More sharing options...
thebadbad Posted November 16, 2009 Share Posted November 16, 2009 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'], '~'); Quote Link to comment https://forums.phpfreaks.com/topic/181662-solved-preg_replace-from-a-database/#findComment-958782 Share on other sites More sharing options...
thebadbad Posted November 17, 2009 Share Posted November 17, 2009 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>'; Quote Link to comment https://forums.phpfreaks.com/topic/181662-solved-preg_replace-from-a-database/#findComment-958795 Share on other sites More sharing options...
gerkintrigg Posted November 17, 2009 Author Share Posted November 17, 2009 yes, i had a "?" in one of the fields... not really sure how, but it's gone now. Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/181662-solved-preg_replace-from-a-database/#findComment-958801 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.