正则表达式匹配关键字(如果没有用大括号括起来)
在 PHP 变量中,我有一些包含一些关键字的文本。这些关键字目前都是大写的。我希望它们保持大写并用大括号括起来,但仅一次。我正在尝试编写升级代码,但每次运行时,它都会将关键字包装在另一组大括号中。
如果是 {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 目前根本无法正常工作,它会删除一些空格,并且在每次运行时都会在大多数(但不是全部)关键字周围放置更多大括号。我做错了什么?有人可以纠正我的正则表达式吗?
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.
What REGEX do I need to use to match the keyword alone without also matching it if it is {KEYWORD}.
For example, the text variable is:
$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";
And my upgrade code is:
$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);
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在寻找否定断言。它们不是使用字符类中的
^
语法编写的,而是使用(? 和
编写的代码>.在你的情况下:(?!...)
(?!...)You are looking for negative assertions. They are not written using the
^
syntax as in character classes but as(?<!...)
and(?!...)
. In your case:为什么是正则表达式?只需使用
str_replace
:Why regex? Just use
str_replace
: