regex - PHP preg_replace replace between slash


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 the result will be:

but also the URL may be like this: 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('', 'page') andstripDir('', 'page')




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:


or per your function:

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

would work for you.

Demo of just modified delimiters:
Demo of original regex:

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:




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


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.