PHP echo part of a string from right to left

shwebdev picture shwebdev · Jul 18, 2012 · Viewed 11.1k times · Source

I am trying to get the ID from the end of this string the 4305 after the -. The code below works from left to right and shows 150. How can i make it work from right to left to show the 4305 after the -?

  $mystring = "150-Adelaide-Street-Brisbane-Cbd-4305";
  $mystring = substr($mystring, 0, strpos($mystring, "-"));
  echo $mystring;

Updated: This does what i need but i'm sure there is a better way to write it:

  $mystring = "150-Adelaide-Street-Brisbane-Cbd-4305";
  $mystring = substr(strrev($mystring), 0, strpos(strrev($mystring), "-"));
  echo strrev($mystring);

Answer

Michael Mior picture Michael Mior · Jul 18, 2012

You can use strrpos to get the last hyphen in the string, and then take the rest of the string after this character.

$mystring = "150-Adelaide-Street-Brisbane-Cbd-4305";
$mystring = substr($mystring, strrpos($mystring, "-") + 1);
echo $mystring;