Jump to content

preg_match to split url


ted_chou12

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
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

Link to comment
Share on other sites

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.