使用 PHP preg_replace 函数进行复杂模式替换,忽略带引号的字符串
考虑以下字符串:
这是一个 STRING,其中包含一些关键字 有可用的。 '我需要格式化 来自 STRING' 的关键字
在上面的字符串关键字中,有 STRING 和 WHERE
现在我需要得到如下输出:
this is a <b>STRING</b> <b>WHERE</b> some keywords ARE available. 'i need TO format the KEYWORDS from the STRING'
这样html 输出将类似于:
这是STRING WHERE一些关键字 有可用的。 '我需要格式化 来自 STRING' 的关键字
请注意,带引号 ('...') 字符串中的关键字将被忽略。在上面的示例中,我忽略了带引号的字符串中的 STRING 关键字。
请提供以下 PHP 脚本的修改版本,以便我可以获得如上所述的所需结果:
$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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这适用于您的字符串示例,但对于更复杂的字符串会出现问题,例如包含带有撇号的单词的字符串。无论如何,它可以作为一个起点。
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.
尝试类似的操作:
重复相同的关键字(具有相同的更改)有点多余 - 使用正则表达式允许您应用这些相同的更改(在这种情况下,将匹配项包装在
;
标签)到所有匹配项。Try something like:
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.