Welcome to WebmasterWorld Guest from 188.8.131.52 , 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 msg:3542423 6:16 pm on Jan 7, 2008 (gmt 0) 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?
RonPK msg:3542441 6:36 pm on Jan 7, 2008 (gmt 0)
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.
jerome msg:3542449 6:41 pm on Jan 7, 2008 (gmt 0)
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.
CWebguy msg:3542485 7:10 pm on Jan 7, 2008 (gmt 0)
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]