Strip string containing URL to the domain, and include subdomain if available - php

Currently, I can strip the domain of the URL string by:
$pattern = '/\w+\..{2,3}(?:\..{2,3})?(?:$|(?=\/))/i';
$url = 'http://www.example.com/foo/bar?hat=bowler&accessory=cane';
if (preg_match($pattern, $url, $matches) === 1) {
echo $matches[0];
}
This will echo:
example.com
The problem is that I want to include the subdomain if it exists.
So for example:
$url = 'http://sub.domain.example.com/foo/bar?hat=bowler&accessory=cane';
Should echo:
sub.domain.example.com
How can I achieve this insanity?

You can use the parse_url() function for this:
$str = 'http://sub.domain.example.com/foo/bar?hat=bowler&accessory=cane';
$parts = parse_url($str);
print_r($parts);
Output:
Array
(
[scheme] => http
[host] => sub.domain.example.com
[path] => /foo/bar
[query] => hat=bowler&accessory=cane
)
Thus:
echo $parts['host'];
Gives you:
sub.domain.example.com

Related

How to get url directory names in php array?

I have url like https://in.pinterest.com/sridharposnic/restinpeace/.
I want url directories without domain in php array.
Example:-
$array[0] = 'sridharposnic';
$array[1] = 'restinpeace';
How we can extract these ?
You can use parse_url() and explode():
$url = 'https://in.pinterest.com/sridharposnic/restinpeace/';
$parsed = parse_url( $url );
$chunks = explode( '/', trim($parsed['path'],'/') );
print_r( $chunks );
Will print:
Array
(
[0] => sridharposnic
[1] => restinpeace
)

PHP Regex to find first 3 match between slash

I have a string like this:
$url = '/controller/method/para1/para2/';
Expected output:
Array(
[0] => 'controller',
[1] => 'method',
[2] => array(
[0] => 'para1',
[1] => 'para2'
)
)
I am trying to build a regex to achieve this but not able to construct the pattern properly.
Please assist.
I tried to use explode function to split,
$split_url = explode('/',$url);
$controller = $split_url[1];
$method = $split_url[2];
unset($split_url[0]);
unset($split_url[1]);
unset($split_url[2]);
$para = $split_url;
But this is really not a great way of doing this and is prone to errors.
whithout regex:
$url = '/controller/method/para1/para2/para3/';
$arr = explode('/', trim($url, '/'));
$result = array_slice($arr, 0, 2);
$result[] = array_slice($arr, 2);
print_r($result);
Note: if you need to always have parameters at the same index (even if there is no method or parameters), you can change $result[] = array_slice($arr, 2); to $result[2] = array_slice($arr, 2);
Here's a slightly nasty method using explode:
$url = '/controller/method/para1/para2/para3/';
# get rid of leading and trailing slashes
$url = trim($url, '/');
$arr = explode('/', $url);
$results = array( $arr[0], $arr[1], array_slice($arr, 2) );
print_r($results);
Output:
Array
(
[0] => controller
[1] => method
[2] => Array
(
[0] => para1
[1] => para2
[2] => para3
)
)
It will work for any number of para elements.
And just to show that regexs are not scary, they're lovely fluffy friendly things, here's a regex version:
preg_match_all("/\/(\w+)/", $url, $matches);
$arr = $matches[1];
$results = array( $arr[0], $arr[1], array_slice($arr, 2) );
It's actually very easy to match this URL -- just search for / followed by alphanumeric characters (\w+).
How about something like:
$url = '/controller/method/para1/para2/para3/';
$regex = '~^/([^/]+)/([^/]+)/(?:(.*)/)?$~';
if(preg_match($regex, $url, $matches)) {
$controller = $matches[1];
$method = $matches[2];
$parameters = explode('/', $matches[3]);
}
This will capture 3 segments separated by a leading/trailing /. The 3rd segment of parameters can then be split with explode(). To get the array exactly like in your question:
$array = array($controller, $method, $parameters);
// Array
// (
// [0] => controller
// [1] => method
// [2] => Array
// (
// [0] => para1
// [1] => para2
// [2] => para3
// )
// )
An alterate way of thinking about this is to actually parse your route to determine the controller and then pass the remaining route components off to the controller to determine what to do.
$url = '/controller/method/para1/para2/para3/';
$route_parts = explode('/', $url, '/')); // we don't need leading and trailing forward slashes
$controller_str = array_shift($route_parts);
$method_str = array_shift($route_parts);
// instantiate controller object be some means (a factory pattern shown here for demo purposes)
$controller = controllerFactory::getInstance($controller_str);
// set method on controller
$controller->setMethod($method_str);
// pass parameters to controller
$controller->setParams($route_parts);
// do whatever with controller
$controller->execute();

can not retrieve part of uri (i am working on kohana)

I have following uri intranet/student/main/schedule
I have to take just the name of the directory which is student, but when I try
basename($_SERVER['SCRIPT_NAME']);
it returns index.php, when I try
basename($_SERVER['REQUEST_URI']);
it retutns schedule. How can I take just student or at least student/main/schedule?
Try this....
$url = 'http://www.examplewebsite.com/intranet/student/main/schedule';
$parsed = parse_url($url);
$exploded = explode('/', $parsed['path']);
$directory = $exploded[2];
echo $directory;
Hope this helps.
You can get directory like this-
dirname('c:/Temp/x'); // returns 'c:/Temp'
OR
You can try this-
<?php
$url = 'http://username:password#hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>
It will gives you
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)

PHP get parameter from URL string (not current page)

I know you can easily get a parameter from the page you're currently on, but can you easily do the same from any URL string?
I need to grab the "id" parameter out of a string like https://market.android.com/details?id=com.zeptolab.ctr.paid?t=W251bGwsMSwxLDIxMiwiY29tLnplcHRvbGFiLmN0ci5wYWlkIl0.
How can I do this with PHP? Is there a built-in function, or do I have to use regex?
You could use combination of parse_url and parse_str:
$url = 'https://market.android.com/details?id=com.zeptolab.ctr.paid?t=W251bGwsMSwxLDIxMiwiY29tLnplcHRvbGFiLmN0ci5wYWlkIl0';
$arr = parse_url($url);
parse_str($arr['query']);
echo $id; //com.zeptolab.ctr.paid?t=W251bGwsMSwxLDIxMiwiY29tLnplcHRvbGFiLmN0ci5wYWlkIl0
Yes you can.
parse_url()
From the PHP docs:
<?php
$url = 'http://username:password#hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>
The above example will output:
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
/path
There's parse_url():
function extractGETParams($url)
{
$query_str = parse_url($url, PHP_URL_QUERY);
$parts = explode('&', $query_str);
$return = array();
foreach ( $parts as $part )
{
$param = explode('=', $part);
$return[$param[0]] = $param[1];
}
return $return;
}
$url = 'http://username:password#hostname/path?arg=value&arg2=value2#anchor';
var_dump( extractGETParams($url) );
On Codepad.org: http://codepad.org/mHXnOYlc
You can use parse_str(), and then access the variable $id.

PHP Array Key & value Question

Hi I writed a test code as below.
<?php
$url = 'http://localhost/events/result/cn_index.php?login';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>
Output
Array ( [scheme] => http [host] => localhost [path] => /events/result/cn_index.php [query] => login ) /events/result/cn_index.php
Now I inserted the line below
echo array[query]; // I want to echo 'login', but failed.
How to get the value of 'login'?
$parsed = parse_url($url);
echo $parsed['query'];
Try with:
$output = parse_url($url, PHP_URL_PATH);
echo $output['query'];

Categories