Jump to content

specifying whole string replacements


gerkintrigg

Recommended Posts

I am using the following code to replace a phrase and a word from a string

<?php 
$string='it leaves a bad taste in my mouth- I only want to replace the second mouth';
$short_word ='mouth';
$phrase='leaves a bad taste in my mouth';
$old_words=array('~\b'.$phrase.'\b(?![^<]*?>)~', '~\b'.$short_word.'\b(?![^<]*?>)~');

$new_words = array(
'<font color="red">'.$phrase.'</font>','<font color="blue">'.$short_word.'</font>');

$string = preg_replace($old_words, $new_words, $string);?><strong><?php 
echo $string;?></strong>

 

I only want to replace the word if it is NOT inside the string. Is there a way of distinguishing that from a preg function.

 

I hope I don't get flamed for posting a similar post to a previous one. I believe this is a new problem...

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/184381-specifying-whole-string-replacements/
Share on other sites

There is no simple method. Given your example you could use a negative lookbehind assersion to say only replace if it's not preceeded by the string giving you the pattern something along the lines of...

 

'#(?<!leaves a bad taste in my )mouth#'

 

But since I doubt your needs are that specific it will get complicated. It sounds like you would have to first write a function to find the position of $short_word within $phrase you would then have to dynamically create the pattern to search and replace with. A completely untested basic theoretical example.

 

// seach the $phrase
preg_match("#(.*?)\b{$word}\b(.*)#", $phrase, $out);

// create pattern for the replace
$pattern = "#(?<!{$out[1]})$word(?!{$out[2]})#";

$string = preg_replace($pattern, "REPLACEMENT", $string);

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.