Jump to content

Recommended Posts

Hi, I have a variable that is either formatted as:

 

http://thedomain.com/id/xxxx/ or

http://thedomain.com/profiles/dzdf/

 

The URL differs each time but is it possible to make a bit of code that extracts the string between the last two forward slashes? That is, if the variable is the first example, it will out put "xxxx" or if the variable is the second one, it will output "dzdf" but the output is not limited to these two. Sorry if I'm being a bit confusing.

 

Any assistance is much appreciated :)

Link to comment
https://forums.phpfreaks.com/topic/241894-get-last-part-of-string/
Share on other sites

You can use preg_match to accomplish this

 

$pattern = '~^http://[\w\d]+\.[com|net|org|gov]/[\w\d]+/([\w\d])+/$~i'; //can add more extensions
$subject = "http://thedomain.com/id/xxxx/";
preg_match($pattern,$subject,$matches);
print $matches[0]; //first match

You can use preg_match to accomplish this

 

$pattern = '~^http://[\w\d]+\.[com|net|org|gov]/[\w\d]+/([\w\d])+/$~i'; //can add more extensions
$subject = "http://thedomain.com/id/xxxx/";
preg_match($pattern,$subject,$matches);
print $matches[0]; //first match

 

Sorry, I'm not very good at PHP, please bear with me...

 

I tried doing this

 


$pattern = '~^http://[\w\d]+\.[com|net|org|gov]/[\w\d]+/([\w\d])+/$~i'; //can add more extensions
$subject = $urlInput
preg_match($pattern,$subject,$matches);
$urlResult = $matches[0]; //first match
(bit of html code here so the php breaks into two)
echo $urlResult

 

 

but it's coming out as blank?

If you are simplying parsing a url, use the parse_url function.

 

$path = parse_url($url, PHP_URL_PATH);
echo $path;

 

And a correction to AyKay's code, the $matches[0] does not return the first match, it returns the fully matched string. $matches[1] returns the first match as identified by the parenthesis.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.