Php 更换支架之间的断裂
我需要帮助。 请假设以下PHP变量Php 更换支架之间的断裂,php,regex,Php,Regex,我需要帮助。 请假设以下PHP变量 $string="Hello this is me on [the line to ] have no clue"; 现在,我想用空格替换括号内的换行符,以获得此结果 Hello this is me on [the line to] have no clue 有什么想法吗? 我知道如何处理所有的换行符,但我不知道如何只处理括号内的换行符 谢谢使用基于正向前瞻的正则表达式 preg_replace('~\n(?=[^\[\]]*\])~', ' ', $s
$string="Hello this
is
me on [the
line
to
] have no clue";
现在,我想用空格替换括号内的换行符,以获得此结果
Hello this
is
me on [the line to] have no clue
有什么想法吗?
我知道如何处理所有的换行符,但我不知道如何只处理括号内的换行符
谢谢使用基于正向前瞻的正则表达式
preg_replace('~\n(?=[^\[\]]*\])~', ' ', $str);
只要使用
希望这有帮助。您可以使用
preg\u replace\u callback
来匹配[…]
子字符串,并仅替换匹配中的换行符:
$s = "Hello this\nis\nme on [the\nline\nto\n] have no clue";
echo preg_replace_callback('/\[\s*([^][]*?)\s*]/', function($m){
return "[" . str_replace("\n", " ", $m[1]) . "]";
}, $s);
看
正则表达式解释:
-打开方括号\[
-0+空格\s*
-除了([^][*?)
和[
之外,尽可能少的0个以上字符]
-0+空格\s*
-右括号]
]
@WiktorStribiżew think input包含平衡括号时。如果他想要确切的函数,则需要使用preg_replaceżcallback
$s = "Hello this\nis\nme on [the\nline\nto\n] have no clue";
echo preg_replace_callback('/\[\s*([^][]*?)\s*]/', function($m){
return "[" . str_replace("\n", " ", $m[1]) . "]";
}, $s);