Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove everything from the first occurrence of a character to the end of a string in PHP

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
like image 503
halocursed Avatar asked Jul 15 '09 13:07

halocursed


3 Answers

Here's one way:

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

Another:

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

Or:

$print = explode(',', $print)[0];
like image 54
Paul Dixon Avatar answered Oct 16 '22 01:10

Paul Dixon


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
like image 12
schmilblick Avatar answered Oct 16 '22 02:10

schmilblick


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];
like image 6
Matthew Groves Avatar answered Oct 16 '22 01:10

Matthew Groves