Regex to remove single characters from string

前端 未结 5 1715
既然无缘
既然无缘 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:33

    How about:

    preg_replace('/(^|\s)[a-z](\s|$)/', '$1', $string);
    

    Note this also catches single characters that are at the beginning or end of the string, but not single characters that are adjacent to punctuation (they must be surrounded by whitespace).

    If you also want to remove characters immediately before punctuation (e.g. 'the x.'), then this should work properly in most (English) cases:

    preg_replace('/(^|\s)[a-z]\b/', '$1', $string);
    

提交回复
热议问题