1

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Interesting how they are exactly the same number of characters :) But which would be more efficient?
@Soule: I imagine the first one (the regular expression would have to be compiled, and then probably in to something that's less efficient - on the other hand, though, it is PHP), but it shouldn't be important.
"Premature optimizations are the root of all evil" ;)
Yeah! It work! I'm just a little confused about the use of "#"...but it worked! Thanks...
@ilSavo: It's a delimiter! Normally, I'd use a slash, but there's a slash in the expression, so I picked something else. Another common delimiter is the tilde.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.