PHP Extract numbers from a string

前端 未结 8 1488
傲寒
傲寒 2021-01-28 08:23

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

if the string = \'make1to6\' i would like to extract the numeric charac

相关标签:
8条回答
  • 2021-01-28 08:26

    You can use this:

    // $str holds the string in question
    if (preg_match('/(\d+)to(\d+)/', $str, $matches)) {
        $number1 = $matches[1];
        $number2 = $matches[2];
    }
    
    0 讨论(0)
  • 2021-01-28 08:32

    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
    
    0 讨论(0)
  • 2021-01-28 08:32

    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

    0 讨论(0)
  • 2021-01-28 08:35

    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...
    }
    
    0 讨论(0)
  • 2021-01-28 08:39

    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");
    
    0 讨论(0)
  • 2021-01-28 08:47
    <?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.

    0 讨论(0)
提交回复
热议问题