i couldn’t find this through google right away, so i’m keeping it here for reference:
in a php script, i wanted to return the address of the current directory, but remove the file name, extension and additional GET-parameters from the url. here’s what i’ve come up with:
<?php
$scripturl = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$scriptpath = eregi_replace('\/[a-z0-9_]*\.php.*', '/', $scripturl);
?>
what the regex code does is look for the last slash in the url (“\/”), then any combination of alphanumeric characters (“[a-z0-9_]*”), followed by the .php file extension (“\.php”) and whatever else there may be in the url (“.*”). the found string is replaced with a single slash (“/”).
i’m sure there’s a better ways to do this, but it’s easy and it works:
example file:
- http://www.thinkoholic.com/test/script.php?var=xy#top
output:
- http://www.thinkoholic.com/test/
trying to find the right expression, i found this tool very helpful: PHP Regular Expression Tester