Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP RegEx Remove Space After Every Comma In String

Tags:

regex

php

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.

like image 300
Tableking Avatar asked Dec 17 '22 17:12

Tableking


1 Answers

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

like image 174
Mark Baker Avatar answered Jan 05 '23 00:01

Mark Baker