9

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

For example,

$print = "50 days,7 hours";

should become

50 days
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
halocursed
  • 2,451
  • 5
  • 27
  • 34

6 Answers6

36

Here's one way:

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

Another:

list($print) = explode(',', $print);

Or:

$print = explode(',', $print)[0];
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Paul Dixon
  • 295,876
  • 54
  • 310
  • 348
12

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
  • 1,917
  • 1
  • 18
  • 25
  • 2
    this works for example given, but would fail if the string did not contain a comma. – Paul Dixon Jul 15 '09 at 13:32
  • The php manual states that `strstr()` should not be used to seek the existence of a substring in a string for performance reasons. https://www.php.net/manual/en/function.strstr.php#:~:text=If%20you%20only%20want%20to%20determine%20if%20a%20particular%20needle%20occurs%20within%20haystack,%20instead. – mickmackusa Jun 25 '21 at 01:04
6

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];
Matthew Groves
  • 25,181
  • 9
  • 71
  • 121
5

You can also use current function:

$firstpart = current(explode(',', $print)); // will return current item in array, by default first

Also other functions from this family:

$nextpart = next(explode(',', $print)); // will return next item in array

$lastpart = end(explode(',', $print)); // will return last item in array
Narek
  • 3,813
  • 4
  • 42
  • 58
3
$string="50 days,7 hours";  
$s = preg_split("/,/",$string);
print $s[0];
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • i cannot imagine why this is down voted. to the down voter , care to explain? – ghostdog74 Jul 15 '09 at 14:19
  • Maybe it was because you used preg_split() which is a bit overkill? – Tom Haigh Jul 15 '09 at 14:41
  • 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 Jul 15 '09 at 15:20
  • >> It may be overkill and inefficient it really doesn't matter. don't be a speed kiddie :) – ghostdog74 Jul 15 '09 at 15:41
  • I'd say that this code-only answer demonstrates the "worst from two worlds". It uses a regular expression for a task that doesn't _need_ a regular expression (splitting on a literal string is what `explode()` is designed to do) AND it generates an array when a string is ultimately desired. There isn't even a limit parameter on the call so it will potentially make many elements in the returned array. I know this is an ancient question, but I can't see any redeeming features of this technique. It works, but I'd never recommend it. – mickmackusa Jun 25 '21 at 01:09
2

If you are going to use strstr() then you need to be 100% sure that a comma will exist in the string or be prepared to handle a false return value. Set its 3rd parameter as true to access all characters before the first occurring comma. If there is no comma, then the return value will be false.

preg_replace() will likely be the least efficient, but it is a single function call and the pattern that I'll use will not mutate the string if a comma is not found. If your input string might have newline characters in it, use the s pattern modifier to allow the dot (.) to match these as well.

strtok() is a concise tool to use, but I find its name to be less expressive / more cryptic than other functions (maybe this is my own personal bias toward strstr(). This may confuse or slow down future readers of your code. This function will return false if the input string has no length.

If you are going to use explode(), then don't ask php to perform more than 1 explosion. The good thing about this function is that if the comma doesn't exist, then it will return the whole string. I prefer not to use explode() because it generates an array from which the first element is accessed -- I prefer to not generate more data than I need.

sscanf() is a little too clumsy for this task since a negated character class needs to be used as well as the null coalescing operator. If the delimiter was a space, then %s could be used, but the null coalescing operator would still be necessary because sscanf() will not make zero-length matches.

Code: (Demo) (Demo if no comma) (Demo if string empty)

"50 days,7 hours" "50 days" ""
strstr($print, ',', true) "50 days" false false
preg_replace('/,.*/', '', $print) "50 days" "50 days" ""
strtok($print, ",") "50 days" "50 days" false
explode(',', $print, 2)[0] "50 days" "50 days" ""
sscanf($print, '%[^,]')[0] ?? $print "50 days" "50 days" ""
mickmackusa
  • 43,625
  • 12
  • 83
  • 136