I need to split a string in PHP by \"-\" and get the last part.
So from this:
abc-123-xyz-789
I expect to get
This code will do that
<?php
$string = 'abc-123-xyz-789';
$output = explode("-",$string);
echo $output[count($output)-1];
?>
As per this post:
end((explode('-', $string)));
which won't cause E_STRICT warning in PHP 5 (PHP magic). Although the warning will be issued in PHP 7, so adding @
in front of it can be used as a workaround.
Since explode()
returns an array, you can add square brackets directly to the end of that function, if you happen to know the position of the last array item.
$email = 'name@example.com';
$provider = explode('@', $email)[1];
echo $provider; // example.com
Or another way is list()
:
$email = 'name@example.com';
list($prefix, $provider) = explode('@', $email);
echo $provider; // example.com
If you don't know the position:
$path = 'one/two/three/four';
$dirs = explode('/', $path);
$last_dir = $dirs[count($dirs) - 1];
echo $last_dir; // four
$string = 'abc-123-xyz-789';
$exploded = explode('-', $string);
echo end($exploded);
EDIT::Finally got around to removing the E_STRICT issue
Just Call the following single line code:
$expectedString = end(explode('-', $orignalString));
The accepted answer has a bug in it where it still eats the first character of the input string if the delimiter is not found.
$str = '1-2-3-4-5';
echo substr($str, strrpos($str, '-') + 1);
Produces the expected result: 5
$str = '1-2-3-4-5';
echo substr($str, strrpos($str, ';') + 1);
Produces -2-3-4-5
$str = '1-2-3-4-5';
if (($pos = strrpos($str, ';')) !== false)
echo substr($str, $pos + 1);
else
echo $str;
Produces the whole string as desired.
3v4l link