我试图在打开括号后删除一个或多个空格,然后在圆括号和方括号的括号中删除。
$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"
但不是后的空格空格!
答案 0 :(得分:10)
试试这个正则表达式:
(?<=[([]) +| +(?=[)\]])
<强> Click for Demo 强>
用空白字符串替换匹配
<强>解释强>
(?<=[([]) +
- 匹配1个以上的空格,前面有[
或(
|
- 或+(?=[)\]])
- 匹配)
或]