Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove single character words from string with preg_replace

Given the following input -

"I went to 1 ' and didn't see p"

, what is the regular expression for PHP's preg_replace function to remove all single characters (and left over spaces) so that the output would be -

"went to and didn't see".

I have been searching for a solution to this but cannot find one. Similar examples haven't included explanations of the regular expression so i haven't been able to adapt them to my problem. So please, if you know how to do this, provide the regular expression but also break it down so that I can understand how it works.

Cheers

like image 709
Mike Mike Avatar asked Dec 05 '25 20:12

Mike Mike


1 Answers

Try this:

$output = trim(preg_replace("/(^|\s+)(\S(\s+|$))+/", " ", $input));
  • (^|\s+) means "beginning of string or space(s)"
  • (\s+|$) means "end of string of space(s)"
  • \S is single non-space character
like image 197
poncha Avatar answered Dec 08 '25 12:12

poncha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!