homepage Welcome to WebmasterWorld Guest from 54.205.99.71
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
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?

Thanks!
Lance

 

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]

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved