Complex pattern replacement using PHP preg_replace function ignoring quoted strings

Posted by Saiful on Stack Overflow See other posts from Stack Overflow or by Saiful
Published on 2010-05-12T05:21:13Z Indexed on 2010/05/12 5:24 UTC
Read the original article Hit count: 232

Filed under:
|
|
|
|

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

© Stack Overflow or respective owner

Related posts about php

Related posts about pattern