regex to remove all whitespaces except between brackets

后端 未结 6 2068
我在风中等你
我在风中等你 2021-01-06 13:01

I\'ve been wrestling with an issue I was hoping to solve with regex.

Let\'s say I have a string that can contain any alphanumeric with the possibility of a substrin

6条回答
  •  太阳男子
    2021-01-06 13:57

    Resurrecting this question because it had a simple solution that wasn't mentioned.

    \[[^]]*\](*SKIP)(*F)|\s+
    

    The left side of the alternation matches complete sets of brackets then deliberately fails. The right side matches and captures spaces to Group 1, and we know they are the right spaces because if they were within brackets they would have been failed by the expression on the left.

    See the matches in this demo

    This means you can just do

    $replace = preg_replace("~\[[^]]*\](*SKIP)(*F)|\s+~","",$string);
    

    Reference

    1. How to match pattern except in situations s1, s2, s3
    2. How to match a pattern unless...

提交回复
热议问题