本文介绍了如果没有用大括号括起来,则正则表达式匹配关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PHP 变量中,我有一些包含一些关键字的文本.这些关键字目前大写.我希望它们保持大写并用大括号括起来,但只有一次.我正在尝试编写升级代码,但每次运行时它都会将关键字包装在另一组大括号中.

In a PHP variable I have some text that contains some keywords. These keywords are currently capitalised. I would like them to remain capitalised and be wrapped in curly brackets but once only. I am trying to write upgrade code but each time it runs it wraps the keywords in another set of curly brackets.

我需要使用什么 REGEX 来单独匹配关键字而不匹配它(如果它是 {KEYWORD}).

What REGEX do I need to use to match the keyword alone without also matching it if it is {KEYWORD}.

例如文本变量为:

$string = "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";

我的升级代码是:

$keywords = array('BLOGNAME', 'BLOGLINK', 'TITLE', 'POST', 'POSTTIME', 'TABLE', 'TABLELINKS', 'PERMALINK', 'TINYLINK', 'DATE', 'TIME', 'MYNAME', 'EMAIL', 'AUTHORNAME', 'LINK', 'CATS', 'TAGS', 'COUNT', 'ACTION');
foreach ($keywords as $keyword) {
    $regex = '|(^\{){0,1}(\b' . $keyword . '\b)(^\}){0,1}|';
    $replace = '{' . $keyword . '}';
    $string = preg_replace($regex, $replace, $string);
}

我的 REGEX 目前根本无法正常工作,它正在剥离一些空格,并且在每次运行时在大多数(但不是全部)关键字周围放置更多大括号.我究竟做错了什么?有人可以纠正我的正则表达式吗?

My REGEX is currently not working well at all, it is stripping some spaces and also on each run placing more curly brackets around most (but not all) keywords. What am I doing wrong? Can someone correct my regex?

推荐答案

您正在寻找 否定断言.它们不像在字符类中那样使用 ^ 语法编写,而是使用 (?<!...)(?!...)代码>.在你的情况下:

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)(?!\})|';

这篇关于如果没有用大括号括起来,则正则表达式匹配关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 21:50