phpregexstringreplacecpu-word

Remove single-letter words (and a leading or trailing space) from a string


I have a string like: Bruce A Johnson

I want it to be Bruce Johnson.

How do I remove the single A from the string with PHP? (all 'words' of only 1 character need to be removed)


Solution

  • Something like this:

    preg_replace('/\b\w\b\s?/', '', $string);
    

    This says remove any single word character that has a word boundary on either side and optionally a trailing space.

    Thus b test a test foo c will yield test test foo.

    If you might have some trailing punctuation (like Bruce A. Johnson) you can get rid of the punctuation with this expression:

    preg_replace('/\b\w\b(\s|.\s)?/', '', $string);
    // 'b test a, test foo c' -> 'test test foo'