tags:

views:

77

answers:

4

In my project I get back a name of a person through a php response. And I store that name in a variable.

So the name could be like James Smith or Sakhu Ali Khan or anything else.

I want to replace the spaces between the names with "."

Suppose I get the James Smith and I will save it in $userName

Now I want to parse $userName and then replace the spaces with "." so my

$parsedUserName == James.Smith

Can anyone tell me how to do this in php. I am not very much familiar with text parsing.

Best Zeeshan

+3  A: 

You can use the str_replace() function to do this:

$parsedUserName = str_replace(' ', '.', $userName);

If you're using UTF-8 or another multibyte character set then you should use mb_str_replace() instead.

$parsedUserName = mb_str_replace(' ', '.', $userName);
Greg
+1 Good answer; it might be worth trimming before you do a replace so you don't end up with something like John.Smith.
Doomspork
what about two spaces? John..Smith
Question Mark
There is no character whose UTF-8 encoded word contains the byte 0x20 other than U+0020.
Gumbo
A: 
Chacha102
I see that this wasn't a specialty question....
Chacha102
A: 

Use:

$parsedUserName = str_replace(array("  ", " "), ".", $userName);

In case you have more than one whitespaces, so:

James        Smith

is replaced with:

James.Smith
inakiabt
A: 

i would use regexp (i can always find an excuse to use it) for catching multiple spaces

$parsedUserName = preg_replace('/ +/','.',trim($userName));
Question Mark