删除括号前后的空格

2022-03-22 00:00:00 regex php preg-replace

我正在尝试删除圆括号和方括号后和前的一个或多个空格。

$s = "This is ( a sample ) [ string ] to play with"

预期结果:

"This is (a sample) [string] to play with"

我设法删除了之前的空格:

$s = preg_replace('/s+(?=[])])/', '', $s);

结果:

"This is ( a sample) [ string] to play with"

而不是括号后的空格!


解决方案

尝试此正则表达式:

(?<=[([]) +| +(?=[)]])

Click for Demo

将匹配项替换为空字符串

说明:

  • (?<=[([]) +-匹配前缀为[(的1+个空格匹配项
  • |-OR
  • +(?=[)]])-匹配出现的1+个空格,后跟)]

相关文章