Shorten from more than 2 spaces to 1 space

I like to change myString which is "Hello,    my  friend!" to "Hello, my friend!"

I used to do it with the code below in coldFusion.


reReplace(variables.myString,"[[:space:]]+"," ","ALL")

I tried to change the coldFusion code above into PHP style like the following.

[b]code[/b]

$myString="Hello,     my  friend!";
$myString=str_reReplace($myString,"[[:space:]]+"," ","ALL");
echo $myString;

The code above poduce an error with the code of “Call to undefined function rereplace().”

How can I make it in PHP?

I use this regex, so your existing one [[space]] should be inserted between the ## delimeters.


$str = preg_replace('#( ){2,}#', ' ', $str );       // rm adjacent spaces
$str = trim($str);

[fphp]preg_replace[/fphp] is one of a family of PHP functions which permit you to re-use the regexes you already depended on in coldFusion.

“Call to undefined function rereplace()” is a very precise message, you are calling a function which does not exist, neither in the base PHP language you are using nor as a function which you have created yourself and this code has access to.

I think you wanted str_replace(), but I doubt it will do what you want in this instance, though its worth a try:


$myString="Hello,     my  friend!";
$myString=str_replace("  "," ", $myString);
echo $myString;

[fphp]str_replace[/fphp] is generally much faster than invoking a regex-style function, but it is very rigid and suitable for really simple replaces (or removes if the second param is an empty string).

See your mistake? You think that by typing coldFusion functions that they will automatically work in PHP, some might, but generally they will not.

Thank you very much, Cups.