Here is the shortest and most efficient single line drawer I can think of:
$firstTwoParts = implode('/', array_slice(explode('/', $str, 3), 0, 2));
This can be wrapped in a function that allows you to control how many parts you want:
function first_n_parts ($str, $n, $delimiter = '/') {
return ($n = (int) $n) ? implode($delimiter, array_slice(explode($delimiter, $str, $n + 1), 0, $n)) : '';
}
... so you can do:
echo first_n_parts($str, 1);
echo first_n_parts($str, 2);
echo first_n_parts($str, 3);
source
share