Becky
Becky

Reputation: 5585

First value comma separated string

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?

Upvotes: 0

Views: 2042

Answers (3)

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

Explode, validate and print.

$values = explode(',',$str);
if(key_exists(0,$values) &&  trim($values[0])!=""){
  echo $values[0];
}  

Upvotes: -1

Indrasis Datta
Indrasis Datta

Reputation: 8618

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);
    

Upvotes: 2

trincot
trincot

Reputation: 350310

You can use strtok:

$firstVal = strtok($str, ",")

Upvotes: 4

Related Questions