I've a PHP file. In this file I need to check, if my URL has the following ending:
www.example.de/dashboard/2/
So the ending can be a number 1 - 99+ which is always at the end of the url between two slashes. I can't use $_GET here. If it is $_GET, it would be easy:
if ( isset($_GET['ending']) ) :
So how can I do this without a parameter in the URL? Thanks for your help!
if(preg_match('^\/dashboard\/(\d+)', $_SERVER['REQUEST_URI'])){
foo();
}
Use regular expression on the request uri
You can make use of parse_url and explode:
$url = 'http://www.example.de/dashboard/2/';
$path = parse_url($url, PHP_URL_PATH); // '/dashboard/2/'
$parts = explode('/', $path); // ['', 'dashboard', '2', '']
$section = $parts[1]; // 'dashboard'
$ending = $parts[2]; // '2'
Demo: https://3v4l.org/dv6Cn
You can also make use of URL rewriting (this is for a Apache-based web server, but you can find simular resources for nginx or any other web servers if need be).
A more dynamic way is to explode and use array_filter to remove empty values then pick the last item.
If the item * 1 is the same as the item then we know it's a number.
(The return from explode is strings so we cant use is_int)
$url = "http://www.example.de/dashboard/2/";
$parts = array_filter(explode("/", $url));
$ending = end($parts);
if($ending*1 == $ending) echo $ending; //2
First you need to target this url to script - in web server config. For nginx and index.php:
try_files $uri #rewrite_location;
location #rewrite_location {
rewrite ^/(.*) /index.php?link=$1&$args last;
}
Second - you need to parse URI. In $end you find what you want
$link_as_array = array_values(array_diff(explode("/", $url), array('')));
$max = count($link_as_array) - 1;
$end = $link_as_array[$max];
I would think this way. If the URL is always the same, or the same format, I'll do the following:
Check for the approx URL.
Split the URL into pieces.
Find if there's the part I am looking for.
Extract the number.
<?php
$url = "http://www.example.de/dashboard/2/";
if (strpos($url, "www.example.de/dashboard") === 7 or strpos($url, "www.example.de/dashboard") === 8) {
$urlParts = explode("/", $url);
if (isset($urlParts[4]) && isNumeric($urlParts[4]))
echo "Yes! It is {$urlParts[4]}.";
}
?>
The strpos with 7 and 8 is for URL with http:// or https://.
The above will give you the output as the numeric part if it is set. I hope this works out.
Related
I have a url and I want to detect the language to save it in the cookies.
This is my url :
https://www.example.com/en/test.php
There are different methods to do it:
1. Method A (explode REQUEST_URI):
echo $_SERVER['REQUEST_URI']; // /en/test.php
$exp = explode('/',$_SERVER['REQUEST_URI']); // explode by slash
$language = $exp[1]; // first element before / (slash)
Get the current url (without serveur) :
$url = $_SERVER['REQUEST_URI']; // gives "/en/test.php"
Then explode it in an array :
$urlParts = explode ('/', $url); // split the url by /
The first element (index 0) is empty (because the string starts with /), and the language is the second one (index 1)
$language = $urlParts[1] ;
Don't forget to check at each steps if the url is OK and the arrayx contains more than 1 element.
Well sorry for the probably misleading title. Wasn't sure how to describe it better.
When accessing the status page I want to get the attached ID. But I don't want to use GET fields (wordpress makes /status?id=2134 to /status/?id=1234 - that's the only reason actually).
So this is my url
http://foo.bar.com/status/1234/
I want to get 1234
Okay fine. I could use something like $_SERVER["REQUEST_URI"] + trim() for example. Probably regex would be the key to get this job done since one could do something like /status/1234/foo/bar/baz/.. But I'm wondering if there is something builtin with PHP to get this part of the url.
Use the parse_url() function, and extract it:
$url = 'http://foo.bar.com/status/1234/';
$path = trim(parse_url($url, PHP_URL_PATH), '/');
$items = explode('/', $path);
$num = array_pop($items);
var_dump($num);
You can also use a regular expression, if that tickles your fancy:
$url = 'http://foo.bar.com/status/1234/';
$path = parse_url($url, PHP_URL_PATH);
preg_match('~/status/(?P<num>\d+)/?~', $path, $result);
$num = isset($result['num']) ? $result['num'] : null;
var_dump($num);
Try to parses a URL and returns an associative array containing any of the various components of the URL that are present using parse_url, explode it using explode and finally select status id using end
Try like this
$url = 'http://foo.bar.com/status/1234/';
$statusId = explode('/',trim(parse_url($url, PHP_URL_PATH), '/'));
print end($statusId);
Demo Ex http://ideone.com/34iDnh
trim- http://php.net/trim
explode-http://php.net/explode
parse_url-[1]: http://php.net/manual/en/function.parse-url.php
I am not much used to using rtrim and Reg expressions. So I wanted to get my doubt cleared about this:
Here is a url: http://imgur.com/r/pics/paoWS
I am trying to use rtrim function on this url to pick out only the 'paoWs' from the whole url.
Here is what i tried:
$yurl = 'http://imgur.com/r/pics/paoWS';
$video_id = parse_url($yurl, PHP_URL_PATH);
$yid=rtrim( $video_id, '/' );
And i am using '$yid' to hotlink the image from imgur. But What I get after trying this function is:
$yid= '/r/pics/paoWS'
How do I solve this?
rtrim is used for trimming down a string of certain characters or whitespace on the right-hand side. It certainly shouldn't be used for your purpose.
Assuming the URL structure will always be the same, you could just do something like this:
$yurl = 'http://imgur.com/r/pics/paoWS';
$video_id = parse_url($yurl, PHP_URL_PATH);
$parts = explode('/', $video_id)
$yid = end($parts);
You sould not use regular expressions (whitch are 'expensive') for a so 'simple' problem.
If you want to catch the last part of the URL, after the last slash, you can do :
$urlParts = explode('/', 'http://imgur.com/r/pics/paoWS');
$lastPart = end($urlParts);
rtim( strrchr('http://imgur.com/r/pics/paoWS' , '/') ); rtrim + strrchr
substr(strrchr('http://imgur.com/r/pics/paoWS', "/"), 1); substr + strrchr
rtrim() returns the filtered value, not the stripped characters. And your usage of it isn't proper too - it strips the passed characters from the right side. And you don't need parse_url() either.
Proper answers have been given already, but here's a faster alternative:
$yid = substr($yurl, strrpos($yurl, '/')+1);
Edit: And another one:
$yid = ltrim(strrchr($yurl, '/'), '/');
I have url in the following types
http://domain.com/1/index.php
http://domain.com/2/index.php
http://domain.com/3/index.php
http://domain.com/4/index.php
I need to retrieve only the number from the url .
for example,
when i visit http://domain.com/1/index.php , It must return 1.
Have a look at parse_url.
$url = parse_url('http://domain.com/1/index.php');
EDIT: Take a look at $_SERVER['REQUEST_URI'], to get the current URL. Use that instead of $url['path'].
Then you can split $url['path'] on /, and get the 1st element.
// use trim to remove the starting slash in 'path'
$path = explode('/', trim($url['path'], '/'));
$id = $path[0]; // 1
Given the information provided, this will do what you ask... it's not what I would call a robust solution:
$url = $_SERVER['PATH_INFO']; // e.g.: "http://domain.com/1/index.php";
$pieces = explode("/", $url);
$num = $pieces[3];
split the server path by forward slashes (explode('/', $_SERVER['REQUEST_PATH']);)
remove empty entry from the beginning
take the first element
make sure it is an integer (intval(), or a simple (int) cast).
No need to use regular expressions for this.
You use preg_match() to match the domain and get the 1st segment.
$domain = http://www.domain.com/1/test.html
preg_match("/http:\/\/.*\/(.*)\/.*/", "http://www.domain.com/1/test.html");
echo $matches[1]; // returns the number 1 in this example.
I have never used regex before and I was wondering how to write a regular expression in PHP that gets the domain of the URL. For example:
http://www.hegnar.no/bors/article488276.ece --> hegnar.no
You dont need to use regexp for this task.
Check PHP's built in function, parse_url
http://php.net/manual/en/function.parse-url.php
Just use parse_url() if you are specifically dealing with URLs.
For example:
$url = "http://www.hegnar.no/bors/article488276.ece";
$url_u_want = parse_url($url, PHP_URL_HOST);
Docs
EDIT:
To take out the www. infront, use:
$url_u_want = preg_replace("/^www\./", "", $url_u_want);
$page = "http://google.no/page/page_1.html";
preg_match_all("/((?:[a-z][a-z\\.\\d\\-]+)\\.(?:[a-z][a-z\\-]+))(?![\\w\\.])/", $page, $result, PREG_PATTERN_ORDER);
print_r($result);
$host = parse_url($url, PHP_URL_HOST);
$host = array_reverse(explode('.', $host));
$host = $host[1].'.'.$host[0];
See
PHP Regex for extracting subdomains of arbitrary domains
and
Javascript/Regex for finding just the root domain name without sub domains
This is the problem when you use parse_url, the $url with no .com or .net or etc then the result returned is bannedadsense, this mean returning true, the fact bannedadsense is not a domain.
$url = 'http://bannedadsense/isbanned'; // this url will return false in preg_match
//$url = 'http://bannedadsense.com/isbanned'; // this url will return domain in preg_match
$domain = parse_url($url, PHP_URL_HOST));
// return "bannedadsense", meaning this is right domain.
So that we need continue to check more a case with no dot extension (.com, .net, .org, etc)
if(preg_match("/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$/i",$domain)) {
echo $domain;
}else{
echo "<br>";
echo "false";
}