tags:

views:

615

answers:

4

I want to remove everything(including the comma) from the first comma of a string in php eg.

$print="50 days,7 hours";

should become "50 days "

+4  A: 

This should work for you:

$r = (strstr($print, ',') ? substr($print, 0, strpos($print, ',')) : $print);
# $r contains everything before the comma, and the entire string if no comma is present
schmilblick
this works for example given, but would fail if the string did not contain a comma.
Paul Dixon
Ah, true! Modified code to handle that.
schmilblick
+6  A: 

Here's one way:

$print=preg_replace('/^([^,]*).*$/', '$1', $print);

Another

list($firstpart)=explode(',', $print);
Paul Dixon
A regex seems like a bit overkill for simple string manipulation?
schmilblick
Regex is a bit of a canon-ball solution to the mosquito problem
My Alter Ego
I like your second example. It's a clever way of getting around that you can't use explode(',', $print)[0]. I would have used array_shift, but I like the list idea better.
Dan Breen
I wanted it to work if the string did not contain a comma.....I took your second solution...thanks a lot
halocursed
+2  A: 

You could use a regular expression, but if it's always going to be a single pairing with a comma, I'd just do this:


$printArray = explode(",", $print);
$print = $printArray[0];
mgroves
Don't you mean $printArray[0]?
My Alter Ego
Yes, I corrected it.
mgroves
+1  A: 
$string="50 days,7 hours";  
$s = preg_split("/,/",$string);
print $s[0];
ghostdog74
i cannot imagine why this is down voted. to the down voter , care to explain?
ghostdog74
Maybe it was because you used preg_split() which is a bit overkill?
Tom Haigh
i don't think its overkill. it solves the problem didn't it.
ghostdog74
and no... i am not the one who down vote you.
ghostdog74
Yeah I think a downvote is unfair. It may be overkill and inefficient but it does work. PHP manual says "If you don't need the power of regular expressions, you can choose faster (albeit simpler) alternatives like explode() or str_split()"
Tom Haigh
>> It may be overkill and inefficientit really doesn't matter. don't be a speed kiddie :)
ghostdog74