替换括号之间的间隔

时间:2016-03-29 13:14:54

标签: 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

有什么想法吗? 我知道如何处理所有换行符,但我不知道如何只解决括号内的换行符。

由于

3 个答案:

答案 0 :(得分:1)

使用基于前瞻性的正面正则表达式。

preg_replace('~\n(?=[^\[\]]*\])~', ' ', $str);

DEMO

答案 1 :(得分:1)

您可以使用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);

请参阅IDEONE demo

\[\s*([^][]*?)\s*]正则表达式解释:

  • \[ - 开放方括号
  • \s* - 0+空白
  • ([^][]*?) - 尽可能少于[]
  • 以外的0个字符
  • \s* - 0+空白
  • ] - 右括号

答案 2 :(得分:0)

只需使用nl2br() function

即可
 echo nl2br($string);

希望这有帮助。