Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 更换支架之间的断裂_Php_Regex - Fatal编程技术网

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

我需要帮助。 请假设以下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(?=[^\[\]]*\])~', ' ', $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);

正则表达式解释:

  • \[
    -打开方括号
  • \s*
    -0+空格
  • ([^][*?)
    -除了
    [
    ]
    之外,尽可能少的0个以上字符
  • \s*
    -0+空格
  • ]
    -右括号

从技术上讲,正则表达式与方括号内的换行符不匹配。仅当它后面跟有
]
@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);