1

I am using php 7.1.8 and I am trying to use $output .= preg_replace('/\s+/', ' ', $output); to replace all spaces in a text that occur more than 1 time.

However, I get the following warning:

Warning: preg_replace(): No ending delimiter '+' found in C:\Users\admin\Desktop\Coding Projects\project\test.php on line 144

I only want to replace spaces. Is there a better way to do this?

I appreciate your replies!

Carol.Kar
  • 3,775
  • 32
  • 114
  • 229
  • The code sample as shown here can not trigger that warning. I'd hazard a guess and say that your test code was not what you've shown here. – mario Sep 09 '18 at 07:22
  • Yet another "an apple is a duplicate of a motor engine!" not-a-dup question on Stack. – John Dec 05 '20 at 10:34

2 Answers2

2

This will search through a string for any place where there is one or more spaces together and then replace it with just one space.

$output = preg_replace('/\s{1,}/', ' ', $output);
Joseph_J
  • 3,641
  • 2
  • 12
  • 22
1

Probably the problem is because you are concatenating the output and preg return must be assigned to a variable. Yo can try to use:

$var_out = preg_replace('/\s+/', ' ', $output);
//and than concatenate to 
$output .= $var_out

or just because you are using php you can also use the str_replace() function like this:

$output .= str_replace(' ', ' ', $output);

hope it helps.

Sigma
  • 377
  • 3
  • 15