Using PHP to find part of a URL - php

Take this domain:
http://www.?.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html
How could i use PHP to find the everything between the first and second slash regardless of whether it changes or no?
Ie. elderly-care-advocacy
Any helo would be greatly appreciated.

//strip the "http://" part. Note: Doesn't work for HTTPS!
$url = substr("http://www.example.com/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html", 7);
// split the URL in parts
$parts = explode("/", $url);
// The second part (offset 1) is the part we look for
if (count($parts) > 1) {
$segment = $parts[1];
} else {
throw new Exception("Full URLs please!");
}

$url = "http://www.example.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html";
$parts = parse_url($url);
$host = $parts['host'];
$path = $parts['path'];
$items = preg_split('/\//',$path,null,PREG_SPLIT_NO_EMPTY);
$firstPart = $items[0];

off the top of my head:
$url = http://www.example.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html
$urlParts = parse_url($url); // An array
$target_string = $urlParts[1] // 'elderly-care-advocacy'
Cheers

explode('/', $a);

All you should do, is parse url first, and then explode string and get first part. With some sanity checks that would lok like following:
$url = 'http://www.?.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html';
$url_parts = parse_url($url);
if (isset($url_parts['path'])) {
$path_components = explode('/', $ul_parts['path']);
if (count($path_components) > 1) {
// All is OK. Path's first component is in $path_components[0]
} else {
// Throw an error, since there is no directory specified in path
// Or you could assume, that $path_components[0] is the actual path
}
} else {
// Throw an error, since there is no path component was found
}

I was surprised too, but this works.
$url='http://www.?.co.uk/elderly-care-advocacy/...'
$result=explode('/',$url)[3];

I think a Regular Expression should be fine for that.
Try using e.g.: /[^/]+/ that should give you /elderly-care-advocacy/ as the second index of an array in your example.
(The first string is /www.?.com/)

Parse_URL is your best option. It breaks the URL string down into components, which you can selectively query.
This function could be used:
function extract_domain($url){
if ($url_parts = parse_url($url), $prefix = 'www.', $suffix = '.co.uk') {
$host = $url_parts['host'];
$host = str_replace($prefix,'',$host);
$host = str_replace($suffix,'',$host);
return $host;
}
return false;
}
$host_component = extract_domain($_SERVER['REQUEST_URI']);

Related

How do I use PHP Function preg_replace() in naming a .txt file after a site URL

How can I name a txt file after a site URL without the preceding https:// or http:// as in: www.google.com.txt?
I think I might be getting it wrong here: fopen($sitenameWithoutHTTP.".txt, "w");
Below is the way I'm trying to address that:
<?php
//
#mkdir("result", 0755);
#chdir("result");
$link = $sitename;
$sitename = preg_replace('#^https?://#', '', $sitenameWithoutHTTP);
$resultfile = fopen($sitenameWithoutHTTP.".txt", "w");
//
?>
Thanks for helping find a fix.
Hope this helps you achieve what you intended!
<?php
$siteName = 'https://www.google.com';
$siteNameWithoutHttps = preg_replace('#^https?://#', '', $siteName);
// print_r($siteNameWithoutHttps);
$resultFile = fopen($siteNameWithoutHttps.".txt", "w");
// run a check
if($resultFile == true) {
echo "success";
} else {
echo "failed";
}
The expected result for the commented print_r above should be:
www.google.com
$arr = ['http','https',':','/','?','&','#','.'];
$sitename = str_replace($arr, '', $sitenameWithoutHTTP);
also you can use base64_encode(), or use parse_url().
$HOST = parse_url($sitenameWithoutHTTP, PHP_URL_HOST);
and if you need to save real URL and get it again I see best way with using Md5 hash
$fileName = md5($sitenameWithoutHTTP).'.txt';
can get it again file.php/?getFile2url=[httpLink]
header('Location: '. Md5($_GET['getFile2url']).'.txt');
exit;

Get the first directory from URL with PHP

I have url in variable like this:
$url = 'http://mydomain.com/yep/2014-04-01/some-title';
Then what I want is to to parse the 'yep' part from it. I try it like this:
$url_folder = strpos(substr($url,1), "/"));
But it returns some number for some reason. What I do wrong?
Use explode, Try this:
$url = 'http://mydomain.com/yep/2014-04-01/some-title';
$urlParts = explode('/', str_ireplace(array('http://', 'https://'), '', $url));
echo $urlParts[1];
Demo Link
Well, first of all the substr(...,1) will return to you everthing after position 1. So that's not what you want to do.
So http://mydomain.com/yep/2014-04-01/some-title becomes ttp://mydomain.com/yep/2014-04-01/some-title
Then you are doing strpos on everthing after position 1 , looking for the first / ... (Which will be the first / in ttp://mydomain.com/yep/2014-04-01/some-title). The function strpos() will return you the position (number) of it. So it is returning you the number 4.
Rather you use explode():
$parts = explode('/', $url);
echo $parts[3]; // yep
// $parts[0] = "http:"
// $parts[1] = ""
// $parts[2] = "mydomain.com"
// $parts[3] = "yep"
// $parts[4] = "2014-04-01"
// $parts[4] = "some-title"
The most efficient solution is the strtok function:
strtok($path, '/')
So complete code would be :
$dir = strtok(parse_url($url, PHP_URL_PATH), '/')
Use parse_url function.
$url = 'http://mydomain.com/yep/2014-04-01/some-title';
$url_array = parse_url($url);
preg_match('#/(?<path>[^/]+)#', $url_array['path'], $m);
$url_folder = $m['path'];
echo $url_folder;

URL - Get last part in PHP

I have my url:
http://domain/fotografo/admin/gallery_bg.php
and i want last part of the url:
gallery_bg.php
but, I do not want to link static, ie, for each page that vistitar I want to get the last part of the url
use following
<?php
$link = $_SERVER['PHP_SELF'];
$link_array = explode('/',$link);
echo $page = end($link_array);
?>
Use basename function
echo basename("http://domain/fotografo/admin/gallery_bg.php");
If it is same page:
echo $_SERVER["REQUEST_URI"];
or
echo $_SERVER["SCRIPT_NAME"];
or
echo $_SERVER["PHP_SELF"];
In each case a back slash(/gallery_bg.php) will appear. You can trim it as
echo trim($_SERVER["REQUEST_URI"],"/");
or split the url by / to make an array and get the last item from array
$array = explode("/",$url);
$last_item_index = count($url) - 1;
echo $array[$last_item_index];
or
echo basename($url);
$url = "http://domain/fotografo/admin/gallery_bg.php";
$keys = parse_url($url); // parse the url
$path = explode("/", $keys['path']); // splitting the path
$last = end($path); // get the value of the last element
you can use basename($url) function as suggested above. This returns the file name from the url. You can also provide the file extension as second argument to this function like basename($url, '.jpg'), then the filename without the extension will be served.
Eg:
$url = "https://i0.com/images/test.jpg"
then echo basename($url) will print test.jpg
and echo basename($url,".jpg") will print test
$url = $_SERVER["PHP_SELF"];
$path = explode("/", $url);
$last = end($path);
Try this:
Here you have 2 options.
1. Using explode function.
$filename = end(explode('/', 'http://domain/fotografo/admin/gallery_bg.php'));
2. Use basename function.
$filename = basename("http://domain/fotografo/admin/gallery_bg.php");
-
Thanks
$basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
$uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
if (strstr($uri, '?')) $uri = substr($uri, 0, strpos($uri, '?'));
$url = trim($uri, '/');
In PHP 7 the accepted solution is giving me the error that only variables are allowed in explode so this works for me.

Parse between slashes within URL

I'm trying to parse two numbers within a URL. The URL is here:
http://movies.actionpaxed.com/5600_5949/5943/5/pics/none/500k/3min/003.jpg?nvb=20130811232301&nva=20130812012301&hash=090a687f7e27b2f5ef735
I'm trying to only get the "5943/5" portion of the URL. I would just parse the URL, then use str_replace, but the folders around the two I need, vary in name.
So far I have:
$homepage = file_get_contents($url);
$link = parse_to_string('"video_url":"', '"};', $homepage);
$link = str_replace(array( '"low":"', '"};'), '', $link);
$link = utf8_decode(urldecode($link));
At the end of this code, $link = http://movies.actionpaxed.com/5600_5949/5943/5/pics/none/500k/3min/003.jpg?nvb=20130811232301&nva=20130812012301&hash=090a687f7e27b2f5ef735
Any help with the regex expression that can take care of this for me, would be greatly appreciated!
How about:
$res = explode('/', parse_url($url, PHP_URL_PATH));
$res = $res[2].'/'.$res[3];
echo $res;
Demo!
$exploded = explode("/", $link);
$res = $exploded[4] . "/" . $exploded[5];
echo $res;
preg_match('%https?://.*?/\d*_\d*/(\d*)/(\d*)%',$link,$matches);
print_r($matches);
Here is a function that extracts what you are looking for.
function getTheStuff($url) {
// Only get the part of the URL that
// actually matters; this makes the
// problem smaller and easier to solve
$path = parse_url($url, PHP_URL_PATH);
// The path will be false if the URL is
// malformed, or null if it was not found
if ($path !== false && $path !== null) {
// Assuming that the stuff you need is
// always after the first forward slash,
// and that the format never changes,
// it should be easy to match
preg_match('/^\/[\d_]+\/(\d+\/\d+)/', $path, $result);
// We only capture one thing so what we
// are looking for can only be the second
// thing in the array
if (isset($result[1])) {
return $result[1];
}
}
// If it is not in the array then it
// means that it was not found
return false;
}
$url = 'http://movies.actionpaxed.com/5600_5949/5943/5/pics/none/500k/3min/003.jpg?nvb=20130811232301&nva=20130812012301&hash=090a687f7e27b2f5ef735';
var_dump(getTheStuff($url));
If I were writing this for myself then I would have avoided the regular expression. It is the easiest in this case, so I used it. I would probably have generalized the solution by tokenizing the $path (using / as a delimiter), and then let another function/method/mechanism handle extracting the parts that are needed. That way it would be easier to adopt it for other URLs that are formatted differently.

Get last word from URL after a slash in PHP

I need to get the very last word from an URL. So for example I have the following URL:
http://www.mydomainname.com/m/groups/view/test
I need to get with PHP only "test", nothing else. I tried to use something like this:
$words = explode(' ', $_SERVER['REQUEST_URI']);
$showword = trim($words[count($words) - 1], '/');
echo $showword;
It does not work for me. Can you help me please?
Thank you so much!!
Use basename with parse_url:
echo basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
by using regex:
preg_match("/[^\/]+$/", "http://www.mydomainname.com/m/groups/view/test", $matches);
$last_word = $matches[0]; // test
I used this:
$lastWord = substr($url, strrpos($url, '/') + 1);
Thnx to: https://stackoverflow.com/a/1361752/4189000
You can use explode but you need to use / as delimiter:
$segments = explode('/', $_SERVER['REQUEST_URI']);
Note that $_SERVER['REQUEST_URI'] can contain the query string if the current URI has one. In that case you should use parse_url before to only get the path:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
And to take trailing slashes into account, you can use rtrim to remove them before splitting it into its segments using explode. So:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', rtrim($_SERVER['REQUEST_URI_PATH'], '/'));
To do that you can use explode on your REQUEST_URI.I've made some simple function:
function getLast()
{
$requestUri = $_SERVER['REQUEST_URI'];
# Remove query string
$requestUri = trim(strstr($requestUri, '?', true), '/');
# Note that delimeter is '/'
$arr = explode('/', $requestUri);
$count = count($arr);
return $arr[$count - 1];
}
echo getLast();
If you don't mind a query string being included when present, then just use basename. You don't need to use parse_url as well.
$url = 'http://www.mydomainname.com/m/groups/view/test';
$showword = basename($url);
echo htmlspecialchars($showword);
When the $url variable is generated from user input or from $_SERVER['REQUEST_URI']; before using echo use htmlspecialchars or htmlentities, otherwise users could add html tags or run JavaScript on the webpage.
use preg*
if ( preg_match( "~/(.*?)$~msi", $_SERVER[ "REQUEST_URI" ], $vv ))
echo $vv[1];
else
echo "Nothing here";
this was just idea of code. It can be rewriten in function.
PS. Generally i use mod_rewrite to handle this... ans process in php the $_GET variables.
And this is good practice, IMHO
ex: $url = 'http://www.youtube.com/embed/ADU0QnQ4eDs';
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url_path = parse_url($url, PHP_URL_PATH);
$basename = pathinfo($url_path, PATHINFO_BASENAME);
// **output**: $basename is "ADU0QnQ4eDs"
complete solution you will get in the below link. i just found to Get last word from URL after a slash in PHP.
Get last parameter of url in php

Categories