0

I want to extract numbers from a string in PHP like following :

if the string = 'make1to6' i would like to extract the numeric character before and after the 'to' substring in the entire string. i.e. 1 and 6 are to be extracted

i will be using these returned values for some calculations.' i would like to extract the numeric character before and after the 'to' substring in the entire string. i.e. 1 and 6 are to be extracted

The length of the string is not fixed and can be a max of 10 characters in length.The number can be of max two digits on either side of 'to' in the string.

Some example string values :

sure1to3
ic3to9ltd
anna1to6
joy1to4val
make6to12
ext12to36

thinking of something like :

function beforeTo(string) {

    return numeric_value_before_'to'_in_the_string;

}


function afterTo(string) {

    return numeric_value_after_'to'_in_the_string;

}

i will be using these returned values for some calculations.

2
  • Have you tried looping through each character and checking if it is_int()? (php.net/is_int) Commented Dec 3, 2011 at 19:54
  • I am confused. Is this task about text extraction, text validation, or both? Commented Aug 9, 2022 at 11:02

8 Answers 8

2

You could use preg_match_all to achive this:

function getNumbersFromString($str) {
    $matches = array();
    preg_match_all('/([0-9]+)/', $str, $matches);
    return $matches;
}
$matches = getNumbersFromString('hej 12jippi77');
Sign up to request clarification or add additional context in comments.

1 Comment

This entire pattern could be simplified to /\d+/. The capture group is unnecessary and [0-9] is more briefly expresses as \d.
1

Use preg_match with a regex that will extract the numbers for you. Something like this should do the trick for you:

$matches = null;
$returnValue = preg_match('/([\d+])to([\d+])/uis', 'ic3to9ltd', $matches);

After this $matches will look like:

array (
  0 => '3to9',
  1 => '3',
  2 => '9',
);

You should read somewhat on regular expressions, it's not hard to do stuff like this if you know how they work. Will make your life easier. ;-)

3 Comments

tested with a string with two digits.... not working with two digits like "m6to12" but works for "m1to6"
The reason it fails with more than one digit is that it uses [\\d+] which really means one character of 0-9 or +, so it would also match a + which is really wrong. Simply writing \d+ would match 1 or more characters of 0-9, which would be better.
Wrapping \d in a character class is pointless. The askers input does not suggest that case insensitive or multibyte matching is required. The s modifier is pointless since there is no . in the pattern. This answer is teaching plenty of bad pattern crafting practices.
0

You can use a regular expression as such, it should match exactly your specification:

$string = 'make6to12';
preg_match('{^.*?(?P<before>\d{1,2})to(?P<after>\d{1,2})}m', $string, $match);
echo $match['before'].', '.$match['after']; // 6, 12

Comments

0

You can use this:

// $str holds the string in question
if (preg_match('/(\d+)to(\d+)/', $str, $matches)) {
    $number1 = $matches[1];
    $number2 = $matches[2];
}

2 Comments

This works, but does not validate that there is only 1 or 2 digits before/after "to", see my answer below for a more strict approach.
@rabusmar - this works great... except it doesnt validate that the digits length should be either 1 or 2.... anyway thanks
0

You can use regular expressions.

$string = 'make1to6';
if (preg_match('/(\d{1,10})to(\d{1,10})/', $string, $matches)) {
    $number1 = (int) $matches[1];
    $number2 = (int) $matches[2];
} else {
    // Not found...
}

Comments

0
<?php

$data = <<<EOF

sure1to3
ic3to9ltd
anna1to6
joy1to4val
make6to12
ext12to36

EOF;

preg_match_all('@(\d+)to(\d+)@s', $data, $matches);
header('Content-Type: text/plain');

//print_r($matches);
foreach($matches as $match)
{
    echo sprintf("%d, %d\n", $match[1], $match[2]);
}

?>

1 Comment

The s pattern modifier is useless because there is no . in the pattern
0

This is what Regular Expressions are for - you can match multiple instances of very specific patterns and have them returned to you in an array. It's pretty awesome, truth be told :)

Take a look here for how to use the built in regular expression methods in php : LINK

And here is a fantastic tool for testing regular expressions: LINK

1 Comment

There isn't much substance in this answer. It could have been a comment under the question.
0
<?php
list($before, $after) = explode('to', 'sure1to3');

$before_to = extract_ints($before);
$after_to  = extract_ints($after);

function extract_ints($string) {
    $ints = array();
    $len = strlen($string);

    for($i=0; $i < $len; $i++) {
        $char = $string{$i};
        if(is_numeric($char)) {
            $ints[] = intval($char);
        }
    }

    return $ints;
}
?>

A regex seems really unnecessary here since all you are doing is checking is_numeric() against a bunch of characters.

1 Comment

It seems entitely possible, to me, that to could occur more than once in the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.