Using regular expression is the first, although it came to me, but I know that it may not be efficient :
$str = 'www.example.com/usa/california/redding/'; $patten = '/(((\/.[0-9A-Za-z]+\/).[0-9A-Za-z]+\/).[0-9A-Za-z]+\/)/'; $ret = preg_match($patten, $str, $matches); var_export($matches);
the output will be:
array ( 0 => '/usa/california/redding/', 1 => '/usa/california/redding/', 2 => '/usa/california/', 3 => '/usa/', )
at first this is a coincidence, the rest 3 is a capture.
source share