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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.