Regex to remove single characters from string

前端 未结 5 1714
既然无缘
既然无缘 2020-12-21 19:05

Consider the following strings

breaking out a of a simple prison
this is b moving up
following me is x times better

All strings are lowerca

5条回答
  •  借酒劲吻你
    2020-12-21 19:20

    As a one-liner:

    $result = preg_replace('/\s\p{Ll}\b|\b\p{Ll}\s/u', '', $subject);
    

    This matches a single lowercase letter (\p{Ll}) which is preceded or followed by whitespace (\s), removing both. The word boundaries (\b) ensure that only single letters are indeed matched. The /u modifier makes the regex Unicode-aware.

    The result: A single letter surrounded by spaces on both sides is reduced to a single space. A single letter preceded by whitespace but not followed by whitespace is removed completely, as is a single letter only followed but not preceded by whitespace.

    So

    This a is my test sentence a. o How funny (what a coincidence a) this is!
    

    is changed to

    This is my test sentence. How funny (what coincidence) this is!
    

提交回复
热议问题