mk_89
mk_89

Reputation: 2742

Smartest way to extract a string number and convert in to int

I need to create a function which will be able to extract string representations of numbers and return them as integers but I'm unsure about the most efficient way to do this.

I was thinking that I could possibly have a dictionary of numbers and look for matches in the string.

Or I could trim away anything that came before the word "third" and after the word "ninth" and process the results.

string

"What is the third, fifth, sixth and ninth characters to question A"

desired output

array(3,5,6,9);

Upvotes: 1

Views: 72

Answers (3)

mlask
mlask

Reputation: 337

Rather ugly code (because of "global"), but simply working

$dict = array('third' => 3, 'fifth' => 5, 'sixth' => 6, 'ninth' => 9);
$string = 'What is the third, fifth, sixth and ninth characters to question A';
$output = null;

if (preg_match_all('/(' . implode('|', array_keys($dict)) . ')/', $string, $output))
    $output = array_map(function ($in) { global $dict; return $dict[$in]; }, $output[1]);

print_r($output);

Update

The exact code without use of "global":

$dict = array('third' => 3, 'fifth' => 5, 'sixth' => 6, 'ninth' => 9);
$string = 'What is the third, fifth, sixth and ninth characters to question A';
$output = null;

if (preg_match_all('/(' . implode('|', array_keys($dict)) . ')/', $string, $output))
    $output = array_map(function ($in) use ($dict) { return $dict[$in]; }, $output[1]);

print_r($output);

Upvotes: 4

Alfred Huang
Alfred Huang

Reputation: 18235

See this, complete work for you!

<?php

function get_numbers($s) {
    $str2num = array(
        'first' => 1,
        'second' => 2,
        'third' => 3,
        'fourth' => 4,
        'fifth' => 5,
        'sixth' => 6,
        'seventh' => 7,
        'eighth' => 8,
        'ninth' => 9,
    );
    $pattern = "/(".implode(array_keys($str2num), '|').")/";
    preg_match_all($pattern, $s, $matches);
    $ans = array();
    foreach($matches[1] as $key) {
        array_push($ans, $str2num[$key]);
    }
    return $ans;
}

var_dump(get_numbers("What is the third, fifth, sixth and ninth characters to question A"));

Upvotes: 2

Lo&#239;c
Lo&#239;c

Reputation: 11943

$string = "What is the first, third, first, first, third, sixth and ninth characters to question A";
$numbers = array('first' => 1, 'second' => 2, 'third' => 3); //...

preg_match_all("(".implode('|',array_keys($numbers)).")", $string, $matches );

$result = array();
foreach($matches[0] as $match){
    $result[] = $numbers[$match];
}

var_dump($result);

Upvotes: 1

Related Questions