Welcome to WebmasterWorld Guest from 126.96.36.199 , register , free tools , login , search , pro membership , help , library , announcements , recent posts , open posts Pubcon Platinum Sponsor 2014
PHP function to get Integer from String CWebguy
Hello, I'm looking for a PHP function that will extract a number from a string. I have tried intval() but that only works if the integer is first in the string. Is there anything to get a number from anywhere in a string?
There's always regular expressions... $string = 'Hello, there are 29 messages waiting for you'; $number = preg_replace("/[^0-9]/", '', $string); // ditch anything that is not a number
$number should now be 29.
This is only works properly if there's just one number in the string, otherwise numbers will be concatenated.
I'd look into regular expressions. With a regexp you could do something like find a serie of any number of digits within any number of other letters or ponctuation.
I'm sure somebody better than me in regexp can offer a precise regexp to do this. Or you can test yours by searching for an "online regexp" website.
Yeah, that's what I figured. I just wasn't sure if I needed to build my own function for it or if PHP had one already. I guess they don't. I guess it's on to learning regex's for me!
Thanks Ron for the code, I'll look more at that and try to incorporate it!
edited by: CWebguy at 7:13 pm (utc) on Jan. 7, 2008]