gpt4 book ai didi

php - preg_replace 当不在双引号内时

转载 作者:可可西里 更新时间:2023-11-01 13:41:26 24 4
gpt4 key购买 nike

基本上我想替换句子中的某些词(例如,“树”一词与“披萨”一词)。限制:当需要替换的单词在双引号之间时,不进行替换。

例子:

The tree is green. -> REPLACE tree WITH pizza
"The" tree is "green". -> REPLACE tree WITH pizza
"The tree" is green. -> DONT REPLACE
"The tree is" green. -> DONT REPLACE
The ""tree is green. -> REPLACE tree WITH pizza

是否可以用正则表达式做到这一点?我会计算单词前双引号的数量,并检查它是奇数还是偶数。但这可能在 php 中使用 preg_replace 吗?

谢谢!

//编辑:

目前我的代码如下所示:

preg_replace("/tree/", "pizza", $sentence)

但是这里的问题是用双引号来实现逻辑。我试过这样的事情:

preg_replace("/[^"]tree/", "pizza", $sentence)

但这不起作用,因为它只检查单词前面是否有双引号。但是上面有这个检查失败的例子。重要的是我只想用正则表达式解决这个问题。

最佳答案

正则表达式不是一种可以满足您每项工作所需的工具。您可以在一定程度上为此使用正则表达式,但对于嵌套引号中的所有情况,它会继续变得更加复杂。

您可以在此处使用Negative Lookahead

$text = preg_replace('/\btree\b(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)/i', 'pizza', $text);

参见 Working demo

正则表达式:

\b               the boundary between a word char (\w) and not a word char
tree 'tree'
\b the boundary between a word char (\w) and not a word char
(?! look ahead to see if there is not:
[^"]* any character except: '"' (0 or more times)
" '"'
(?: group, but do not capture (0 or more times)
(?: group, but do not capture (2 times):
[^"]* any character except: '"' (0 or more times)
" '"'
){2} end of grouping
)* end of grouping
[^"]* any character except: '"' (0 or more times)
$ before an optional \n, and the end of the string
) end of look-ahead

另一种选择是使用受控回溯,因为您可以在 中执行此操作

$text = preg_replace('/"[^"]*"(*SKIP)(*FAIL)|\btree\b/i', 'pizza', $text);

参见 Working demo

想法是跳过引号中的内容。我首先匹配引号后跟除 " 之外的任何字符后跟引号,然后使子模式失败并强制正则表达式引擎不使用 (*SKIP )(*FAIL) 回溯控制动词。

关于php - preg_replace 当不在双引号内时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20767089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com