July 18, 2012

PHP echo part of a string from right to left

Question by shwebdev

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 by Michael Mior

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;

Answer by Starx

Most easiest way is definitely using explode.

By using explode, you can split the string into an array with each parts accessible as individual identifiers using the indexes.

Usage Example:

  $mystring = "150-Adelaide-Street-Brisbane-Cbd-4305";
  $mystring = explode("-", $mystring);
  echo $mystring[count($mystring)-1]; //Extract the last item
...

Please fill the form - I will response as fast as I can!