How to remove single character words from string with preg_replace
php, preg-replace, regex
Solution
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
Problem
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