PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How to get part of a URL?

 November 20, 2022     php, preg-replace, regex, regex-greedy, regex-group     No comments   

Issue

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;

Solution

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



Answered By - Emma
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing