Jump to content

Recommended Posts

barand gave me this answer after i gave him a preg_match expression that did the same.

 

Quote from Barand:

<?php
$a = parse_url('http://sub.domain.tld:8080/foldera/folderb/index.php?request=value');
echo '<pre>', print_r($a, true), '</pre>';

?>

---

 

just for ref my preg_match is:

 

its a regex with preg_match that will store all parts of a domain name into an array, eg:

 

http://sub.domain.tld:8080/foldera/folderb/index.php?request=value

 

will return:

 

Array(

[ 0] => "http"

[ 1] => "sub.domain.tld"

[ 2] => "8080"

[ 3] => "/foldera/folderb/"

[ 4] => "index.php"

[ 5] => "?request=value"

)

 

-----------

Now the function that does this: (The above noted output is stored in $matches2 variable)

 

preg_match('/\A(http:\/\/|https:\/\/)*([a-zA-Z0-9_\-\.]+):*([0-9]+)*\/*([a-zA-Z0-9_\-\.]+\/)*(.*\.\w*)*(\?.*)*/i',$url,$matches2);

 

hope this helps,

 

Link to comment
https://forums.phpfreaks.com/topic/97055-extract-data-from-url/#findComment-496628
Share on other sites

There is a builtin function that does that: parse_url().

 

<?php
$url = 'http://www.bookshop.com/book/en/catalog.php?id=12345';
$pu = parse_url($url);
echo '<pre>' . print_r($pu,true) . '</pre>;
?>

 

Will give you

Array
(
    [scheme] => http
    [host] => www.bookshop.com
    [path] => /book/en/catalog.php
    [query] => id=12345
)

 

Ken

 

Link to comment
https://forums.phpfreaks.com/topic/97055-extract-data-from-url/#findComment-496643
Share on other sites

Yes, you can use PHP's parse_url() function to accomplish that. And in case if you want to retrieve just either the domain name or query string, you can pass in an optional component parameter to the parse_url() function. It will then return a string instead of an array.

 

<?php

  $url = 'http://www.bookshop.com/book/en/catalog.php?id=12345';

 

  // to return just the domain name

  echo parse_url($url, PHP_URL_HOST);

?>

 

Details see code example at: http://www.thewebscripter.com/tutorial/code_examples/parse_url.php

 

Hope this helps.

 

Alex

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/97055-extract-data-from-url/#findComment-496810
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.