Hey all. I have a string of names separated by commas. I'm exploding this string of names into an array of names with the comma as the delimiter. I need a RegEx to remove a white space(if any) only after the comma and not the white space between the first and last name.
So as an example:
$nameStr = "Sponge Bob,Bart Simpson, Ralph Kramden,Uncle Scrooge,Mickey Mouse";
See the space before Ralph Kramden? I need to have that space removed and not the space between the names. And I need to have any other spaces before names that would occur removed as well.
P.S.: I've noticed an interesting behavior regarding white space and this situation. Take the following example:
When not line breaking an echo like so:
$nameStr = "Sponge Bob,Bart Simpson, Ralph Kramden,Uncle Scrooge,Mickey Mouse";
$nameArray = explode(",", $nameStr);
foreach($nameArray as $value)
{
echo $value;
}
The result is: Sponge BobBart Simpson Ralph KramdenUncle ScroogeMickey Mouse
Notice the white space still there before Ralph Kramden
However, when line breaking the above echo like so:
echo $value . "<br />";
The output is:
Sponge Bob
Bart Simpson
Ralph Kramden
Uncle Scrooge
Mickey Mouse
And all of the names line up with what appears to be no white space before the name.
So what exactly is PHP's behavior regarding a white space at the start of a string?
Cheers all. Thanks for replies.
What's with today's fixation on using regexp to solve every little problem
$nameStr = "Sponge Bob,Bart Simpson, Ralph Kramden,Uncle Scrooge,Mickey Mouse";
$nameArray = explode(",", $nameStr);
foreach($nameArray as $value)
{
echo trim($value);
}
EDIT
PHP's behaviour re white space is to treat it as the appropriate character and do what it's told by you. HTML's behaviour (or at least that of web browsers) is rather different... and you'll need to learn and understand that difference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With