tags:

views:

61

answers:

3

Hi guys, I've got a string that comes from a POST form where I want to replace all spaced with some other character.

Here's that I did:

$cdata = str_replace(" ","#",$cdata);

And I got this.

--- Contact-ID#=#148 [10274da8]#Sinhronizācija#=#private [1000137d]#Uzvārds#=#Zom [1000137c]#Vārds#=#Tana [1000130e]#Tālrunis#=#3333 [1000130e]#Mobilais#=#5555

As you can see, spaced before "[10..." are still there. Any ideas what could be the problem?

+1  A: 

You need preg_replace here:

$cdata = preg_replace('/\s+/', '#', cdata);
Sarfraz
You don't really need to use regex for such simple thing. There's other problem in this case as Calvin L describes.
Ondrej Slinták
@Ondrej Slinták: That's right, he spotted the problem, no need for regex here.
Sarfraz
yea... tried $cdata = preg_replace('/\s+/', '#', $cdata); , doesn't seem to work...
@user296516: It is because of the reason figured out by Calvin.
Sarfraz
yes, but str_replace of all whitespace characters ( " ", "\t","\n","\r","\o","\x0B" ) doesn't seem to work either...
+4  A: 

It's mostly likely because it's a newline character, \n. The first param of str_replace can be an array of characters to replace. Could also be a tab char. Or use preg_replace to replace all whitespace chars instead.

EDIT:

$chars_to_replace = array(" ", "\t","\n","\r","\o","\x0B");
$new_string = str_replace($chars_to_replace, "#", $cdata);

Calvin L
Hmm... very strange, I replaced all whitespace characters in the manual ( " ", "/t","/n","/r","/o","/x0B" ) and it still doesn't seem to work... any other ideas?
You're using the wrong slash (forward slash). You need to use a backslash (/).
Calvin L
I totally had that backwards. Backslash = \
Calvin L
LOL, thanks. edited the slash, $cdata = str_replace("\t","#",$cdata); ... still the same problem.
Aha... I tried this $cdata = preg_replace("/[^a-zA-Z0-9\s]/", "#", $cdata); and it actually removed that mystical whitespace, as well as lost of other useful characters, but still it shows that its some whitespace character to blame... what else could it be?
added: after preg_replace("/[^a-zA-Z0-9\s]/", "#", $cdata); I see #r#n where the whitespaces where. Yet if I try $cdata = str_replace("\r\n","#",$cdata); it doesn't help.
Try this:$chars = array(" ", "\t", "\n"); $cdata = str_replace($chars, "#", $cdata);
Calvin L
A: 

GOT IT!!! HA-HA-HA! Being a good programmer I had used mysqli_real_escape_string on $_POST before assigning it to $cdata. Now I removed it and seems to work perfect! Thanks guys!