PHP: Last n characters to a specified character in a string?

92 views Asked by At

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)

6

There are 6 answers

1
Gian Marco Toso On BEST ANSWER

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!";
}
0
mjohns On

Should do it in one line...

 substr($string, strrpos($string, '-') + 1);
0
codeneuss On

And there is always a regex for it:

preg_match('/.*-([0-9]+)$/',$yourstring,$match);
echo $match[1];
0
Domain On

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;
0
Ganesan Karuppasamy On

you can use this function to solve ur problem.

 return is_numeric(array_pop(explode('-', $string)));
0
kenorb On

Try the following one-liner:

$substring = (int)end((explode("-", $string)));

it'll be always numeric (0 if invalid number).