I need to extract numbers that appear before a colon in a string for instance: 14:hey-the-bear or 1432:happy-candy I need to grab the 14 or 1432
A tough one... or not. $string = '1432:happy-candy'; echo (int) $string; // Can use typecasting echo ' ' , PHP_EOL; echo intval('14:hey-the-bear'); // Or intval, or any other similar function/cast that does the same thing. PHP: Dan.
Or you can do it with regular expressions. $string = '1432:happy-candy'; preg_match('~(\d+)\:~', $string, $matches); if (isset($matches[1])) { // $matches[1] is what you're looking for } PHP:
I was waiting for this so I could criticize... You should only use the Regular expression engine when it's not possible using a single function call, as initializing it is VERY slow (relatively.) I would post a normal functional way but I'm drunk atm, so I'm thinking better of it... Dan.
You can try this: $string = "14:hey-the-bear"; echo strstr($string, ':', true); //should return the number 14 PHP:
To the last 2 posts, that will only work on PHP 5.3+ - I'm all for using it, but fails miserably for portability. Dan.
I assume that the string is of the only format you have given and the number is BEFORE the colon. $parts = explode (':',$string); $number = $parts[0]; if(is_numeric($number)) { print $number; } Code (markup): This would perfectly according to info given by you.