regex - PHP preg_replace replace between slash

598

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_###/ fromhttp://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 removepage_5 from following URLS...stripDir('http://my-domain.com/search/page_5/order_asc', 'page') andstripDir('http://my-domain.com/search/order_asc/page_5', 'page')

410

Answer

Solution:

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

954

Answer

Solution:

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

People are also looking for solutions to the problem: php - Trouble with checking empty value

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.