I can't figure out how to write the right pattern for my preg_replace pattern.
My situation is this: I've got an URL, let's suppose this:
$url = "first/second/third/fourth"
Now, I need to remove only the last "/" and all the characters after that. So my result should become like this:
first/second/third
For this moment I solved this way:
$result = substr($url, 0, (strrpos($url, "/")));
but I know there should be the right patter to be writted into my preg_replace.
Any suggestion?
Use what you have; it's simple and efficient. Less parentheses could make it look less complicated:
$result = substr($url, 0, strrpos($url, '/'));
The regular expression would look like this:
$result = preg_replace('#/[^/]*$#', '', $url);
Just as long, slightly more confusing.
Match a slash, followed by zero or more characters that are not slashes, followed by the end of the string:
preg_replace("/[^/]*$", "", $url)
Or, using a non-greedy match (*?
), this should also work:
preg_replace("/.*?$", "", $url)