输入示例:
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);
答案 0 :(得分:1)
如果你想替换那些中有单词的那些,你为什么还要替换空括号?我用regex和preg_replace_callback中的递归来解决它:
echo preg_replace_callback('/\((?!\s)([^()\r\n]*|(?R))*\)/',
function($matches) {
# $matches is an array that includes all strings matches by regex
return str_replace(['(', ')'], ['[', ']'], $matches[0]);
}, $text);`
$ text是您的输入文字。
产生的输出如下:
这,(不会被替换),但[这将]和[这] 将被替换,[[this]]和[] [] [] [[]]。如果可能,也 []))。多线(不会被替换)。