-1

How can I remove all the parts from url except base url and first part. There is no certainty in number of parts. Base url is variable. I tried some regex but in vain.

$url =  http://www.example.com/part1/part2/part3/part4;
base_url = parse_url($url, PHP_URL_HOST); // Outputs www.example.com

$desired_output = http://www.example.com/part1;
0

1 Answer 1

5

Here we can use a preg_replace, with a simple expression, maybe similar to:

(.+\.com\/.+?\/).+

where we are capturing our desired output using this capturing group:

(.+\.com\/.+?\/)

and then we swipe to the end of string and replace it with $1.

Test

$re = '/(.+\.com\/.+?\/).+/m';
$str = 'http://www.example.com/part1/part2/part3/part4';
$subst = '$1';

$result = preg_replace($re, $subst, $str);

echo $result;

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here


For all domains .com or not, we might be able to solve it with this expression:

(.+\..+?\/.+?\/).+

Test

$re = '/(.+\..+?\/.+?\/).+/m';
$str = 'http://www.example.com/part1/part2/part3/part4';
$subst = '$1';

$result = preg_replace($re, $subst, $str);

echo $result;

Demo

1
  • 1
    Many thanks for your effort. It works. But my base url is a variable. It may contain .com or .org or any tld. Your answer works only for .com. I have updated my question. Please have a look.
    – SkyRar
    May 29, 2019 at 0:40

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.