How do I drop all text after a comma?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
webcan
Forum Commoner
Posts: 66
Joined: Tue Oct 28, 2003 2:25 pm
Location: Toronto, Canada

How do I drop all text after a comma?

Post by webcan »

I was wondering if anyone could help me come up with a more efficient way of doing this ...

If $var = "Chicago, IL", and I want $var2 just to be "Chicago", this is what I do now:

Code: Select all

$var = "Chicago, IL";
$vartemp = explode(",", $var, 2);
$var2 = $vartemp[0];
I know there must be an easier way to do this.

Any ideas? :)

Thanks!
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Post by Grim... »

From a coding point of view:

Code: Select all

$var = thisFunction("Chicago, IL");


function thisFunction($text)
{
    $vartemp = explode(",", $text, 2);
    return = $vartemp[0];
}
What I suspect you really want is a regular expression.
webcan
Forum Commoner
Posts: 66
Joined: Tue Oct 28, 2003 2:25 pm
Location: Toronto, Canada

Post by webcan »

I suspect I want a regular expression too ;-)

I've always been mystified at constructing them. Any suggestion for what the expression for this would be?

(Do you know of any newbie guide to expressions online btw?)

Thanks.
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Post by Grim... »

You need the crash course: viewtopic.php?t=33147

There is a specific subforum for regex help: viewforum.php?f=38
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

using explode() is likely the more effecient way, technically speaking, rather than regex, as initializing the regex engine and running it could easily take more time than required to break the string once on the comma.
Post Reply