« Book review: "The End of Faith", by Sam Harris | Main | Why the new location-based reminders in iPhone iOS 5 are killing me slowly »

September 16, 2010

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00e553c0af3288330134876c8a37970c

Listed below are links to weblogs that reference Extracting a number from a string in PHP:

Comments

Sasha

Why not to use PHP support for Regular Expressions?

http://www.php.net/manual/en/function.preg-match-all.php

Nick Desbarats

Sasha!

I don't know a lot about regex's, but as I understand them, it would be difficult/impossible to write one that handles the examples in my post correctly, or cases like these:

"12.1 L per 100 k.m." should return "12.1" (and not "12.1100..").

"14 MP3 players" should return "14" (and not "143").

"On-site employees: 200" should return "200" (and not "-200").

"33,333" should return "33333", but "33,,333" should return "33".

"3,333.3" should return "3333.3", but "3.333,3" should return "3.333".

Is it possible to write a regex string that would handle cases like these?

Sasha

Yes, it's possible.
For example this regex will much any optionally signed floating point number in the text:
"[-+]?[0-9]*\.?[0-9]+"

Comma in the number (33,333) is a different case since you want to strip it out rather then just match it.

Sasha

"[-+]?[0-9,]*\.?[0-9]+"
- works for all your examples.

You can remove ',' from the result as a second step.

mbt sandals

Why not to use PHP support for Regular Expressions?

oakley outlet

One thing I know: The only ones among you who will be really happy are those who will have sought and found how to serve.

Flash Mp3 player

My co-worker got a hamp mod and now herpayments were lowered considerably. I need one.

Vivek

Thanks Sasha your regex worked really well :)

Eye Beauty Review

Thanks for sharing! Fantastic article, I can’t wait to view more. These aircraft’s are something different.

chat software download

These days, it is possible for Wii owners to cleverly run an unlock software and have access to complete the additional features without having to kill their gadget.

The comments to this entry are closed.

Your email address:


Powered by FeedBlitz

My Photo

About Nick Desbarats & this blog

  • I'm the founder and CEO of ChoiceBot Inc., which develops the MyChoiceBot interactive product review creation tool for bloggers and product reviewers, as well as the ChoiceBot for e-Retailers decision-assisting tool for shopping sites.

    Contact me any time at nickd choicebot com or 1 (877) 538-9511 x704.

  • Subscribing to this blog gets you notifications of ChoiceBot updates, announcements and Nick's Deep Thoughts.

Twitter Updates

    follow me on Twitter