prigero
prigero

Reputation: 563

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

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

Answers (6)

kenorb
kenorb

Reputation: 166677

Try the following one-liner:

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

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

Upvotes: 0

Domain
Domain

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

Ganesan Karuppasamy
Ganesan Karuppasamy

Reputation: 367

you can use this function to solve ur problem.

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

Upvotes: 0

codeneuss
codeneuss

Reputation: 905

And there is always a regex for it:

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

Upvotes: 0

mjohns
mjohns

Reputation: 369

Should do it in one line...

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

Upvotes: 0

Gian Marco Toso
Gian Marco Toso

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

Related Questions