0

Possible Duplicate:
Converting words to numbers in PHP

I need a function to convert textual numbers to numbers. For example: convert("nine") outputs 9

I know I could write a function like for example if ($number == "one") { $number = 1; } etc... but that would be a lot of work.

Community
  • 1
  • 1
kheom
  • 1

2 Answers2

0

Use the switch statement.

phillip
  • 2,618
  • 19
  • 22
  • How many `case` s that would be? Let's see: 1,2,3,4,5,6... 100,...1000, ... 128434520346.... oh I'm too tired to count any further... – Felix Kling Dec 11 '10 at 22:10
  • @Felix Kling: Given a 32-bit system, just over 2 billion. – BoltClock Dec 11 '10 at 22:12
  • @BoltClock: But I have a 64-bit system :-P *You* can continue counting.... ;) :D – Felix Kling Dec 11 '10 at 22:13
  • Oh that's very different than 0-9 which is what I thought you wanted. You are looking for a natural language parser then. I haven't done that before. Sorry – phillip Dec 11 '10 at 22:14
0

Use a lookup table like this:

$numbers = array(
    'zero' => 0,
    'one' => 1,
    'two' => 2,
    'three' => 3,
    'four' => 4,
    'five' => 5,
    'six' => 6,
    'seven' => 7,
    'eight' => 8,
    'nine' => 9
);

$digit = strtolower($digit);

if (isset($numbers[$digit])) {
    $digit = $numbers[$digit];
}

Note I use strtolower just in case. Of course, this solution would be impractical for anything over a couple dozen. Beyond that, you'll need some sort of parser.

Jonah
  • 9,991
  • 5
  • 45
  • 79