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_###/
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')
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:or per your function:
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
Answer
Solution: