开发者

Remove single letters 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 chara开发者_JAVA技巧cter need to be removed)


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'


Use explode() to split up the three words, remove the middle element of the returned array, and then implode() to rejoin the string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜