Complex pattern replacement using PHP preg_replace function ignoring quoted strings
- by Saiful
Consider the following string:
this is a STRING WHERE some keywords
ARE available. 'i need TO format the
KEYWORDS from the STRING'
In the above string keywords are STRING and WHERE
Now i need to get an output as follows:
this is a <b>STRING</b> <b>WHERE</b> some keywords ARE available. 'i need TO format the KEYWORDS from the STRING'
So that the html output will be like:
this is a STRING WHERE some keywords
ARE available. 'i need TO format the
KEYWORDS from the STRING'
Note that the keywords within a quoted ('...') string will be ignored. in the above example i ignored the STRING keyword within the quoted string.
Please give a modified version of the following PHP script so that I can have my desired result as above :
$patterns = array('/STRING/','/WHERE/');
$replaces = array('<b>STRING</b>', '<b>WHERE</b>');
$string = "this is a STRING WHERE some keywords ARE available. 'i need TO format the KEYWORDS from the STRING'";
preg_replace($patterns, $replaces, $string);