Jump to content

Recommended Posts

Hi, how can a preg_match code that split a url into domain, page at once?

I found:

preg_match('@^(?:http://)?([^/]+)@i', $link, $final);

This doesnt work, only get rid of the http://, I wish to come up with something that deletes "http://" and splits the rest of the url to two parts, the domain and the page:

http://phpfreaks.com/forums/page12.php

The result can be something like:

echo $final[0] gives phpfreaks.com/

echo $final[1] gives forums/page12.php

Thanks,

Ted  :D

Link to comment
https://forums.phpfreaks.com/topic/126116-preg_match-to-split-url/
Share on other sites

For things like this, you don't need regex. You can utilize parse_url() instead.

 

$url = parse_url('http://phpfreaks.com/forums/page12.php');
echo '<pre>';
   print_r($url);
echo '</pre>';

 

output:

Array
(
    [scheme] => http
    [host] => phpfreaks.com
    [path] => /forums/page12.php
)

 

So in otherwords, you can simply output something like:

echo $url['path']; // which outputs: /forums/page12.php

 

Cheers,

 

NRG

 

EDIT: In the event you don't want the first slash in $url['path'], you can instead echo like this:

echo substr($url['path'], 1, strlen($url['path'])-1); // ouputs: forums/page12.php

It's good that you caught that though  :)

I learned something new (as you can tell, I don't make use of substr() often). But know I know there's no need for that extra parameter.. makes coding-life easier for sure. Thanks again for the insight.

 

Cheers,

 

NRG

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.