Steven
Steven

Reputation: 249

Remove extra white space with str_replace

The title and the code is pretty much self explanatory...

but just to clarify more...

I want to stay with a single space between each word inside $myString (and remove bad words)...

I prefer to stay in single line if possible...

$myString = 'There    will      be     no   extra    space       here !!!';

str_replace(array("bad words","another bad words","\s+"), '', $myString);

I'm expecting to get :

There will be no extra space here !!!

Thanks!

Upvotes: 0

Views: 865

Answers (4)

Rudger
Rudger

Reputation: 889

I think you want:

$myString = 'There    will      be     no   extra    space       here !!!';

str_replace(array("bad words","another bad words","\s\s"), array("","", " "), $myString);

You can use an array in the $replace param, which indexed elements relace those of the $search param.

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

Upvotes: 0

Jaykumar Patel
Jaykumar Patel

Reputation: 27614

View Demo Live

str_replace replaces a specific occurrence of a string. and in your case you have to remove only white space not need to replace so preg_replace is best suit for your case.

To remove all unwanted white space you just do as such,

Code

<?php

$myString = 'There    will      be     no   extra    space       here !!!';
echo str_replace('/\s+/', ' ',$myString);

?>

str_replace and preg_replace both produce same result. you can see on here

Result

There will be no extra space here !!!

Upvotes: 2

Halayem Anis
Halayem Anis

Reputation: 7785

print (preg_replace('/ +/', ' ', $myString));

Upvotes: 1

Bhavya Shaktawat
Bhavya Shaktawat

Reputation: 2512

Try this

$myString =     preg_replace('/\s\s*/', ' ',$myString);

Upvotes: 2

Related Questions