Mike Mike
Mike Mike

Reputation: 1135

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

Upvotes: 3

Views: 5295

Answers (4)

poncha
poncha

Reputation: 7866

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

Upvotes: 5

buckley
buckley

Reputation: 14089

You'll need two passes

The first is to strip out all single characters

(?<=^| ).(?=$| ) replace with empty string

The second one is to leave only single spaces

[ ]{2,} replace with single space

You will end up with a string that has possibly spaces in the beginning or the end. I would just trim this with your language instead of doing that with a regex

As an example, the first regex is written in php like

$result = preg_replace('/(?<=^| ).(?=$| )/sm', '', $subject);

Upvotes: 1

xkeshav
xkeshav

Reputation: 54022

try with help of implode, explode and array_filter

$str ="I went to 1 ' and didn't see p";
$arr = explode(' ',$str);
function singleWord($var)
{
  if(1 !== strlen($var))
  return $var;
}
$final = array_filter($arr,'singleWord');

echo implode(' ',$final);
//return "went to and didn't see"(length=19)

Upvotes: 1

Guard
Guard

Reputation: 6955

try this regexp

'\s+\S\s+' -> ' '

Upvotes: 0

Related Questions