Match number at the end of the string

前端 未结 3 1037
旧时难觅i
旧时难觅i 2020-12-16 15:06

Given the following string how can I match the entire number at the end of it?

$string = \"Conacu P PPL Europe/Bucharest 680979\";

I have t

相关标签:
3条回答
  • 2020-12-16 15:34

    You could use a regex with preg_match, like this :

    $string = "Conacu P PPL Europe/Bucharest 680979";
    
    $matches = array();
    if (preg_match('#(\d+)$#', $string, $matches)) {
        var_dump($matches[1]);
    }
    

    And you'll get :

    string '680979' (length=6)
    

    And here is some information:

    • The # at the beginning and the end of the regex are the delimiters -- they don't mean anything : they just indicate the beginning and end of the regex ; and you could use whatever character you want (people often use / )
    • The '$' at the end of the pattern means "end of the string"
    • the () means you want to capture what is between them
      • with preg_match, the array given as third parameter will contain those captured data
      • the first item in that array will be the whole matched string
      • and the next ones will contain each data matched in a set of ()
    • the \d means "a number"
    • and the + means one or more time

    So :

    • match one or more number
    • at the end of the string

    For more information, you can take a look at PCRE Patterns and Pattern Syntax.

    0 讨论(0)
  • 2020-12-16 15:43

    The following regex should do the trick:

    /(\d+)$/
    
    0 讨论(0)
  • 2020-12-16 15:43

    EDIT: This answer checks if the very last character in a string is a digit or not. As the question https://stackoverflow.com/q/12258656/1331430 was closed as an exact duplicate of this one, I'll post my answer for it here. For what this question's OP is requesting though, use the accepted answer.


    Here's my non-regex solution for checking if the last character in a string is a digit:

    if (ctype_digit(substr($string, -1))) {
        //last character in string is a digit.
    }
    

    DEMO

    substr passing start=-1 will return the last character of the string, which then is checked against ctype_digit which will return true if the character is a digit, or false otherwise.

    References:

    1. substr
    2. ctype_digit
    0 讨论(0)
提交回复
热议问题