How to get the first occurrence?

posted by iup85 on 2009-07-06 10:25:22
Hey!
I have a string like that:
 
$s="123-this-is-a-test";
 
How can I only get 123 ?
Then, I have to check if it's a numeric.
(is not 3 chars long always)
dail avatar
dail
12
 
$s="123-this-is-a-test";
$id = strstr($s, '-', true);
if (is_numeric($id))
    echo "It is a number";
else
    echo "It is not a number";
 
The third parameter of strstr() has been added to the 5.3.0 PHP version.
If you are using an older php version you should do:
 
$s="123-this-is-a-test";
$id = explode('-', $s, 1);
if (is_numeric($id[0]))
    echo "It is a number";
else
    echo "It is not a number";
 
Bye
49 answers - 0 questions
  Positive        Negative

gregoriohc avatar
gregoriohc
1
Other shorter way:
$s="123-this-is-a-test";
if (is_numeric(array_shift(explode('-', $s))))
    echo "It is a number";
else
    echo "It is not a number";
?>
1 answers - 0 questions
+ 1  Positive        Negative



Answer the question



Top Users
  • dail (12)
  • livin52 (3)
  • camu (3)
  • softweb (2)
  • Nadine (1)
  • Josware (1)
  • lfelipecr (1)
  • gregoriohc (1)
  • Mitu (1)
  • ryan714 (1)