Search code examples
phpregexsubstrstrpos

Regex to Remove Everything After 4th Slash in URL


I'm working in PHP with friendly URL paths in the form of:

/2011/09/here-is-the-title
/2011/09/here-is-the-title/2

I need to standardize these URL paths to remove anything after the 4 slash including the slash itself. The value after the 4th slash is sometimes a number, but can also be any parameter.

Any thoughts on how I could do this? I imagine regex could handle it, but I'm terrible with it. I also thought a combination of strpos and substr might be able to handle it, but cannot quite figure it out.


Solution

  • You can use explode() function:

    $parts  = explode('/', '/2011/09/here-is-the-title/2');
    $output = implode('/', array_slice($parts, 0, 4));