PHP Regex get url segments

php, regex

Solution

Try

$url = explode('/', trim($url, '/'));
$first_segment = $url[0];
$second_segment = $url[1];

Edit: As pointed out by @Crisp in the comments, to prevent an empty first_segment, `trim` your string before you `explode` it.

Problem

can anybody please help? i want to get the first two segments of a url for example the url can look like this ``` /catalog/category-1 ``` or ``` /catalog/category-1/filter/value ``` my current regex look like this... ``` /(\/catalog\/.*?)\// ``` This will work for the long url but not for the first example.

Original source