Reputation: 249
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
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
Reputation: 27614
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,
<?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
There will be no extra space here !!!
Upvotes: 2
Reputation: 2512
Try this
$myString = preg_replace('/\s\s*/', ' ',$myString);
Upvotes: 2