Regex to remove single characters from string

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

    You could try something like this:

    preg_replace('/\b\S\s\b/', "", $subject);
    

    This is what it means:

    \b    # Assert position at a word boundary
    \S    # Match a single character that is a “non-whitespace character”
    \s    # Match a single character that is a “whitespace character” (spaces, tabs, and line breaks)
    \b    # Assert position at a word boundary
    

    Update

    As raised by Radu, because I've used the \S this will match more than just a-zA-Z. It will also match 0-9_. Normally, it would match a lot more than that, but because it's preceded by \b, it can only match word characters.

    As mentioned in the comments by Tim Pietzcker, be aware that this won't work if your subject string needs to remove single characters that are followed by non word characters like test a (hello). It will also fall over if there are extra spaces after the single character like this

    test a  hello 
    

    but you could fix that by changing the expression to \b\S\s*\b

提交回复
热议问题