remove everything after first comma from string in php

后端 未结 5 2031
闹比i
闹比i 2020-12-31 21:13

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

相关标签:
5条回答
  • 2020-12-31 21:29

    Here's one way:

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

    Another

    list($firstpart)=explode(',', $print);
    
    0 讨论(0)
  • 2020-12-31 21:34

    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
    
    0 讨论(0)
  • 2020-12-31 21:37
    $string="50 days,7 hours";  
    $s = preg_split("/,/",$string);
    print $s[0];
    
    0 讨论(0)
  • 2020-12-31 21:47

    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
    
    0 讨论(0)
  • 2020-12-31 21:47

    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];
    
    0 讨论(0)
提交回复
热议问题