Reputation: 563
I want to get the last n characters from a string, after the last "-" character. Like:
$string = "something-123";
$substring = 123;
$string2 = "something-253672-something-21";
$substring2 = 21;
These characters can only be numbers. How can I do this with PHP? (sorry for bad english)
Upvotes: 0
Views: 84
Reputation: 166677
Try the following one-liner:
$substring = (int)end((explode("-", $string)));
it'll be always numeric (0
if invalid number).
Upvotes: 0
Reputation: 11808
Following code will work according to your query:
$mystring ="something-253672-something-21";
// Get position of last '-' character.
$pos = strrpos($mystring, "-");
// Get number after '-' character.
$last_number = substr($mystring,$pos+1);
echo $last_number;
Upvotes: 0
Reputation: 367
you can use this function to solve ur problem.
return is_numeric(array_pop(explode('-', $string)));
Upvotes: 0
Reputation: 905
And there is always a regex for it:
preg_match('/.*-([0-9]+)$/',$yourstring,$match);
echo $match[1];
Upvotes: 0
Reputation: 369
Should do it in one line...
substr($string, strrpos($string, '-') + 1);
Upvotes: 0
Reputation: 12136
You could explode the string and parse the last element of the resulting array:
$splitted = explode("-", $string);
$numbers = end($splitted);
if (is_numeric($numbers)) {
echo "Yay!";
} else {
echo "Nay!";
}
Upvotes: 5