0

I have this string:

467:some-text-here-1786

How can I select only the first numerical value before the ":" ?

Thank you

  • possible duplicate of [get number in front of 'underscore' with php](http://stackoverflow.com/questions/2220998/get-number-in-front-of-underscore-with-php) – Gordon Sep 06 '11 at 16:48
  • possible duplicate of [Return the portion of a string before the first occurence of a character in php](http://stackoverflow.com/questions/3766301/return-the-portion-of-a-string-before-the-first-occurrence-of-a-character-in-php) – Gordon Sep 06 '11 at 16:54
  • possible duplicate of [How to extract all text in front of @ in a string](http://stackoverflow.com/questions/6273679/how-to-extract-all-text-in-front-of-the-character-in-a-string) – Gordon Sep 06 '11 at 17:00
  • more http://stackoverflow.com/search?q=string+before+character – Gordon Sep 06 '11 at 17:00

4 Answers4

6

Very simple:

list($var) = explode(":",$input);

or

$tmp = explode(":",$input);
$var = array_shift($tmp);

or (as pointed out by PhpMyCoder)

$tmp = current(explode(":",$input));
Kokos
  • 9,051
  • 5
  • 27
  • 44
1
$string = '467:some-text-here-1786';
$var = (int)$string;

Since you're extracting a number, this is enough :) For an explanation of why this works, check the official PHP manual: http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion

It's also really fast and really safe: you are sure you get a number.

ItalyPaleAle
  • 7,185
  • 6
  • 42
  • 69
1
$a = "467:some-text-here-1786";
$a = explode(":", $a);
$a = $a[0];
Pheonix
  • 6,049
  • 6
  • 30
  • 48
0

another way to do this:

$length = strpos($string, ':') + 1;
$number = substr($string, 0, $length);
Hugo Mota
  • 11,200
  • 9
  • 42
  • 60