开发者

Complex pattern replacement using PHP preg_replace function ignoring quoted strings

Consider the following string:

this is a STRING WHERE some keywords A开发者_开发技巧RE 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);


This will work with your string example, but there will be problems with more complicated strings, for example those containing words with apostrophes. Anyway, it may be used as a starting point.

$keywords = array("STRING", "WHERE");
$regexp = '/(\'[^\']+\')|\b(' . implode('|', $keywords) . ')\b/e';
preg_replace($regexp, "strlen('\\2') ? '<b>\\2</b>' : '\\0'", $string);


Try something like:

$keywords = array(
  'STRING' ,
  'WHERE' ,
  'KEYWORDS'
);
$keywordsRE = array();
foreach( $keywords as $w ) {
  $keywordsRE[] = '/\b('.$w.')\b/';
}
$string = "this is a STRING WHERE some keywords KEYWORDS ARE available. 'i need TO format the KEYWORDS from the STRING'";
$stringParts = explode( "'" , $string );
foreach( $stringParts as $k => $v ) {
  if( !( $k%2 ) )
    $stringParts[$k] = preg_replace( $keywordsRE , '<b>$1</b>' , $v );
}
$stringReplaced = implode( "'" , $stringParts );

Repeating the same keywords (with the same changes) is a bit redundant - using a Regular Expression allows you to apply those same changes (in this case, wrapping the matches in <b></b> tags) to all matches.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜