更新时间:2022-03-03 23:26:52
您不需要任何条件结构来跳过引号内的内容.有两种方式.
You do not need any conditional constructs to skip what is inside quotes. There are two ways.
使用与带引号的子字符串匹配的替代分支并使用 (*SKIP)(*FAIL)
动词:
Use an alternative branch matching a quoted substring and use (*SKIP)(*FAIL)
verbs:
preg_replace('/"[^"]*"(*SKIP)(*F)|creat(?:e|ing)/i', 'make', $input)
模式详情:
"[^"]*"
- 匹配 "
,然后是除 "
之外的 0+ 个字符,然后是 "
(*SKIP)(*F)
- 使正则表达式引擎丢弃当前匹配的文本并从当前索引开始|
- 或...creat(?:e|ing)
- 匹配 create
或 creating
."[^"]*"
- matches "
, then 0+ characters other than "
and then a "
(*SKIP)(*F)
- make the regex engine discard the currently matched text and proceed from the current index|
- or...creat(?:e|ing)
- match create
or creating
.参见演示
另一种方法是仅使用捕获和使用 preg_replace_callback
,您可以在其中检查组是否匹配(并适当地建立替换逻辑):
Another way is mere using capturing and using preg_replace_callback
where you can check if a group was matched (and base the replacement logic appropriately):
preg_replace_callback('/("[^"]*")|creat(?:e|ing)/i', function($m) {
return !empty($m[1]) ? $m[1] : 'make';
}, $input)
查看 IDEONE 演示
模式详情:
("[^"]*")
- 第 1 组(稍后可以使用替换模式中的 $1
引用) - 双引号字符串|
- 或creat(?:e|ing)
- 匹配 create
或 creating
.("[^"]*")
- Group 1 (can be later referenced with $1
from the replacement pattern) - a double quoted string|
- orcreat(?:e|ing)
- match create
or creating
.注意"[^"]*"
是一个示例正则表达式,如果你需要匹配带有转义序列的C字符串,你至少应该使用"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"
(在代码中).
Note that "[^"]*"
is a sample regex, if you need to match C strings with escaped sequences, you should use at least "[^"\\\\]*(?:\\\\.[^"\\\\]*)*"
(in the code).