输入示例:
This, ( will not be replaced ) ,
but (this will) and also (this) will be replaced,
also ((this)) and () ()() (()).
If possible, also ())).
Multiline (will not
be replaced).
输出示例:
This, ( will not be replaced ) ,
but [this will] and also [this] will be replaced,
also [[this]] and [] [][] [[]].
If possible, also []]].
Multiline (will not
be replaced).
如您所见,我想用另一种类型的括号替换括号字符,前提是它们包含没有额外空格的单词。
替换应该只在同一行中进行,因此如果打开(在第 1 行中,关闭)在另一行中,则无需更换。
这可能吗?
一个糟糕的尝试:
preg_replace('/([a-zA-Z0-9]+/', '[', $s);
preg_replace('/[a-zA-Z0-9]+)/', ']', $s);
如果你想替换那些有单词的单词,那你为什么也替换空括号呢?我在正则表达式中用递归解决了它,preg_replace_callback:
echo preg_replace_callback('/((?!s)([^()rn]*|(?R))*)/',
function($matches) {
# $matches is an array that includes all strings matches by regex
return str_replace(['(', ')'], ['[', ']'], $matches[0]);
}, $text);`
$text是您的输入文本。
产生的输出如下:
这个,(不会被取代),但[这将]和[这个] 将被替换,也包括 [[此]] 和 [] [][] [[]]。 如果可能的话,也 [])).多行(不会被替换)。