Search code examples
phpsubstr

PHP Remove the last part of the string, determined by first character occurrence, starting from the end of the string


The strings always end with a hyphen followed by a variable size integer. For instance:

foo-bar-baz-132 another-55-string-961370

How can I remove the last hyphen (first occurrence from right to left) plus any character to the right?


Solution

  • try this

    $string = 'foo-bar-baz-132 another-55-string-961370';
    $result = substr ($string , 0, strrpos($string, '-'));
    echo $result;
    

    Source