PHP Extract numbers from a string

前端 未结 8 1489
傲寒
傲寒 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:47

    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. ;-)

    0 讨论(0)
  • 2021-01-28 08:51
    <?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]);
    }
    
    ?>
    
    0 讨论(0)
提交回复
热议问题