Search code examples
phpstringsubstr

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)


Solution

  • 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!";
    }