Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

PHP function to get Integer from String



6:16 pm on Jan 7, 2008 (gmt 0)

5+ Year Member

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?



6:36 pm on Jan 7, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

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.


6:41 pm on Jan 7, 2008 (gmt 0)

5+ Year Member

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.


7:10 pm on Jan 7, 2008 (gmt 0)

5+ Year Member

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]


Featured Threads

Hot Threads This Week

Hot Threads This Month