简体   繁体   中英

Match number at the end of the string

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 to tell that the lenght of the string is not constant.

My language of choice is PHP.

Thanks.

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 .

以下正则表达式应该可以解决问题:

/(\d+)$/

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

To get the number at the end of a string, without using regex:

function getNumberAtEndOfString(string $string) : ?int 
{
  $result = sscanf(strrev($string), "%d%s");
  if(isset($result[0])) return strrev($result[0]);
  return null;
}
var_dump(getNumberAtEndOfString("Conacu P PPL Europe/Bucharest 680979")); //int(680979)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM