Steven Matthews
Steven Matthews

Reputation: 11275

Trying to cut off the file portion of a URI/URL

I'm trying to cut the last portion of a URI as such:

public://path1/path2/path3/filename.extension

Ultimately I just want public://path1/path2/path3/ or public://path1/path2/path3

I've tried using explode, but that seems to have some trouble with :// part of the URL. I'm trying to see if there's a way to do it with substr and strpos.

Any ideas?

Oh, I wasn't clear, I meant PHP.

Upvotes: 2

Views: 65

Answers (2)

Andy Lester
Andy Lester

Reputation: 93636

This might not be a job for regexes, but for existing tools in your language of choice. Regexes are not a magic wand you wave at every problem that happens to involve strings. You probably want to use existing code that has already been written, tested, and debugged.

In PHP, use the parse_url function.

Perl: URI module.

Ruby: URI module.

.NET: 'Uri' class

Upvotes: 1

niconoe
niconoe

Reputation: 1321

My proposal:

$url = 'http://public/protected/private/filename.php';
$url = str_replace(strrchr($url, '/'), '', $url);
echo $url; // Displays: http://public/protected/private

Docs:

Upvotes: 1

Related Questions