How to remove single character words from string w

2019-07-20 23:39发布

问题:

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

回答1:

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


回答2:

try this regexp

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


回答3:

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)


回答4:

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);