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
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:
#
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 /
)()
means you want to capture what is between them
preg_match
, the array given as third parameter will contain those captured data()
\d
means "a number"+
means one or more timeSo :
For more information, you can take a look at PCRE Patterns and Pattern Syntax.
The following regex should do the trick:
/(\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: