How can I create a PHP function to remove or replace all single-character words in a string?

Solution 1: Using Regex

You can use a regular expression to strip out single-letter words from a string:


$str = trim(preg_replace('@(^|\pZ)\pL\pM*(?=\pZ|$)@u', ' ', $str));

\pL → matches any letter.

\pM* → matches optional combining marks.

\pZ → matches any separator (like whitespace).

The regex ensures only single-letter words are removed.

If you instead want to remove any single character (not just letters), you can adjust the pattern like this:


$str = trim(preg_replace('@(^|\pZ)\P\Z(?=\pZ|$)@u', ' ', $str));

Solution 2: Using explode() and implode()

You can split the string into words, filter out single-character ones, and then rebuild the string:


$string = "A Quick Brown B C D Fox";

$array = explode(' ', $string);

foreach ($array as $key => $value) {
    if (strlen($value) == 1) {
        unset($array[$key]); // remove single-character words
    }
}

$string = implode(" ", $array);
echo $string; // Output: Quick Brown Fox

explode(‘ ‘, $string) → splits the sentence into words.

strlen($value) == 1 → checks if a word has only one character.

unset($array[$key]) → removes that word.

implode(” “, $array) → puts the remaining words back together.