preg_replace 仅当不在块中时

preg_replace only if not in a block

我尝试使用 preg_replace 将括号替换为下划线,除非这些括号位于代码块中

例子:

this is my {text}
And this is <code>if (true) { echo "hello world" }</code>
And also a multine line one 
<code>
if (true) { echo "hello world" }
</code>
Another {my super text}

我必须输出:

this is my _text_
And this is <code>if (true) { echo "hello world" }</code>
And also a multine line one 
<code>
if (true) { echo "hello world" }
</code>
Another _my super text_

谢谢

您需要先将代码块与文本块分开。您可以使用 strpos() and substr() 的组合来做到这一点。

我想我已经搞定了,需要更多测试但似乎没问题

preg_replace("<code(?:\s+\w+)*>.*?</code>(*SKIP)(*FAIL)|\{|\})is", "_", $text);