Regex to match keyword if not enclosed by curly braces

送分小仙女□ 提交于 2019-12-04 19:13:22

You are looking for negative assertions. They are not written using the ^ syntax as in character classes but as (?<!...) and (?!...). In your case:

'|(?<!\{)(\b' . $keyword . '\b)(?!\})|';
  • It will work if keyword does not contain special char.
  • (A1) rows can be removed from regex, if source text can not contain {keyword} or necessary to leave '{}' symbols around keywords in result text (was {keyword} need {{keyword}} for formatting as example)

$text = <<<EOF
BLOGNAME has posted COUNT new item(s),

TABLE

POSTTIME AUTHORNAME

You received this e-mail because you asked to be notified when new updates are posted.
Best regards,
MYNAME
EMAIL
EOF;

$aKeywords = array('BLOGNAME', 'BLOGLINK', 'TITLE', 'POST', 'POSTTIME', 'TABLE', 'TABLELINKS', 'PERMALINK', 'TINYLINK', 'DATE', 'TIME', 'MYNAME', 'EMAIL', 'AUTHORNAME', 'LINK', 'CATS', 'TAGS', 'COUNT', 'ACTION');
$keywords = implode('|', $aKeywords);

$reSrch = '/
            (?<!\{)             # (A1) prev symbol is not {
            \b                  # begin of word
            ('.$keywords.') # list of keywords
            \b                  # end of word
            (?!\{)              # (A1) next symbol is not {
            /xm';               //  m - multiline search & x - ignore spaces in regex

$reRepl = '{\1}';

$result = preg_replace($reSrch, $reRepl, $text);

echo '<pre>';
// echo '$reSrch:'.$reSrch.'<hr>';
echo $result.'<br>';

Why regex? Just use str_replace:

foreach ($keywords as $k) {
  $string = str_replace($k, '{'.$k.'}', $string);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!