0

Am trying to replace comma followed by multiple spaces and & symbol with & using php. Is there any way to do it

 example: a,     & b.
  expected output: a & b.

I have tried but it works for only single space. doesn't work for multiple dynamic spaces. Here is my sample code

$var = "a,   & b.";
$var = str_replace(', &','&',$var);

1 Answers1

1

You could use preg_replace and match , +& and replace with a whitespace followed by an &

That would match a comma, one or more whitespaces + followed by an ampersand &. To match any horizontal whitespace character you might also use ,\h+&

$var = "a,   & b.";
$var = preg_replace('/, +&/',' &',$var);
echo $var;

Test

The fourth bird
  • 154,723
  • 16
  • 55
  • 70