Zeeshan Rang
Zeeshan Rang

Reputation: 19915

text parsing in php

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

Upvotes: 0

Views: 167

Answers (4)

Question Mark
Question Mark

Reputation: 3606

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

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

Upvotes: 0

inakiabt
inakiabt

Reputation: 1963

Use:

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

In case you have more than one whitespaces, so:

James        Smith

is replaced with:

James.Smith

Upvotes: -1

Tyler Carter
Tyler Carter

Reputation: 61577

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

Make sure the sanatize the data you get first however. Use things like [trim()][1] and [filter_var()][2] to make sure the data is what you expect it to be.

So do something like this:

$userName = trim($userName); $userName = filter_var($userName, FILTER_SANITIZE_STRING); $parsedUserName = str_replace(" ", ".", $userName);

Upvotes: 0

Greg
Greg

Reputation: 321824

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);

Upvotes: 4

Related Questions