douruoshen1449
2016-08-17 09:52 阅读 49
已采纳

第一个值以逗号分隔的字符串

There will be a string with a single or multiple with no commas at all.

$str = "a, b";

How do I get the first value before the comma if it contains comma(s)? This is what I did.

if(preg_match('/[,]+/', $str, $f)) {
     $firstVal = $f[0];
}

NOTE: Is /^[^,]+/ better suited?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    dongzaocheng3214 dongzaocheng3214 2016-08-17 09:59

    You can use strtok:

    $firstVal = strtok($str, ",")
    
    点赞 评论 复制链接分享
  • doulezhi5326 doulezhi5326 2016-08-17 09:54

    There are several ways to achieve this.

    1. Using substr() and strpos()

      echo substr($str,0,strrpos($str,','));
      
    2. Using explode()

      $result = explode(',',$str);
      echo $result[0];
      
    3. Using strstr()

      echo strstr($str, ',', true);
      
    点赞 评论 复制链接分享
  • doupeng3501 doupeng3501 2016-08-17 09:57

    Explode, validate and print.

    $values = explode(',',$str);
    if(key_exists(0,$values) &&  trim($values[0])!=""){
      echo $values[0];
    }  
    
    点赞 评论 复制链接分享

相关推荐