1

I have a PHP function which is supposed to remove a value with its starting / and ending / from a given URL.

for example: remove /page_###/ from http://my-domain.com/search/page_2/order_asc. the result will be: http://my-domain.com/search/order_asc.

but also the URL may be like this: http://my-domain.com/search/order_asc/page_2. there is no ending / in the end;

function stripDir($url, $mask){
    return preg_replace('/' . $mask . '[\s\S]+?/', '', $url);
}

the above function should be able to remove page_5 from following URLS... stripDir('http://my-domain.com/search/page_5/order_asc', 'page') and stripDir('http://my-domain.com/search/order_asc/page_5', 'page')

0

2 Answers 2

3

The /s in your current regular expression are delimiters, not the starting and ending characters you are looking for. Try changing the delimiter and it should work. Also if the trailing / is optional you should modify the regex I think:

~/page_[\s\S]+?(/|\z)~

or per your function:

~/' . $mask . '[\s\S]+?(/|\z)~

would work for you.

Demo: https://regex101.com/r/sH7bE2/3
Demo of just modified delimiters: https://regex101.com/r/sH7bE2/2
Demo of original regex: https://regex101.com/r/sH7bE2/1

Also since you are checking for the starting and ending / you're going to want to re-place one of those /s.

With substitution demo: https://regex101.com/r/sH7bE2/4

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

Comments

2
function stripDir($url, $mask) {
    return preg_replace('/\/' . preg_quote($mask, '/') . '[^\/]+/', '', $url);
}

1 Comment

Answers should have a write up with them.

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.