[php] Splitting strings in PHP and get last part

I need to split a string in PHP by "-" and get the last part.

So from this:


I expect to get


This is the code I've come up with:

substr(strrchr($urlId, '-'), 1)

which works fine, except:

If my input-string does not contain any "-", I must get the whole string, like from:


I need to get back


and it needs to be as fast as possible. Any help is appreciated!

This question is related to php string

The answer is

split($pattern,$string) split strings within a given pattern or regex (it's deprecated since 5.3.0)

preg_split($pattern,$string) split strings within a given regex pattern

explode($pattern,$string) split strings within a given pattern

end($arr) get last array element




$strArray = explode('-',$str)
$lastElement = end($strArray)

Will return the last element of a - separated string.

And there's a hardcore way to do this:

$str = '1-2-3-4-5';
echo substr($str, strrpos($str, '-') + 1);
//      |            '--- get the last position of '-' and add 1(if don't substr will get '-' too)
//      '----- get the last piece of string after the last occurrence of '-'

Similar questions with php tag:

Similar questions with string tag: