0

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!

Steven
  • 249
  • 5
  • 14

4 Answers4

2

Try this

$myString =     preg_replace('/\s\s*/', ' ',$myString);
Bhavya Shaktawat
  • 2,504
  • 1
  • 13
  • 11
  • Yes I know that trick but I was wondering if it's possible to do it inside : str_replace(array("bad words","another bad words","\s+{2}"), '', $myString); – Steven Dec 11 '14 at 08:41
2

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 !!!
Community
  • 1
  • 1
Jaykumar Patel
  • 26,836
  • 12
  • 74
  • 76
  • Yes I know that trick but I was wondering if it's possible to do it inside str_replace (without using another extra line)... – Steven Dec 11 '14 at 08:44
1
print (preg_replace('/ +/', ' ', $myString));
Halayem Anis
  • 7,654
  • 2
  • 25
  • 45
  • Yes I know that trick but I was wondering if it's possible to do it inside str_replace (without using another extra line)... – Steven Dec 11 '14 at 08:44
0

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 ] )
Rudger
  • 851
  • 8
  • 9