Search code examples
phpregexpreg-matchanchor

Checks if a string ends with a number in php


I want to do a test of variable that starts with a string that I know; and it ends with a number that I don't know, so the test that I did is:

foreach ($json as $key => $value) {
    if ($key == 'IF-MIB::ifDescr.'."$[0-9]")
        echo $key . '=>' . $value . '<br/>';
}

I tested with this, but it doesn't work.


Solution

  • Like this:

    $str = 'IF-MIB::ifDescr1';
    
     if(preg_match('/^IF-MIB::ifDescr([0-9]+)$/', $str, $match)){
          echo $match[1];
     }
    

    Outputs:

     1
    

    Live Demo

    So putting it all together for your use case:

    foreach ($json as $key => $value) {
       if (preg_match('/^IF-MIB::ifDescr[0-9]+$/', $key)){
           echo $key . '=>' . $value . '<br/>';
       }
    }
    

    The ^ at the starts denotes that the string must start with I, and the extra brackets and plus this time state that after the IF-MIB::ifDescr, there can be any number of numbers.

    Just to explain:

    • ^ is Start of string
    • IF-MIB::ifDescr match literal string
    • [0-9] character set 0 through 9, + one or more times "greedy"
    • $ end of string

    And in the first one

    • (...) capture group, which is used to return what is matched inside it.

    So $match[1] is what is captured by the first capture group, $match[0] is the full match.