i have this URI.
http://localhost/index.php?properties&status=av&page=1
i am fetching basename of the URI using following code.
$basename = basename($_SERVER['REQUEST_URI']);
the above code gives me following string.
index.php?properties&status=av&page=1
i would want to remove the last variable from the string i.e &page=1. please note the value for page will not always be 1. keeping this in mind i would want to trim the variable this way.
Trim from the last position of the string till the first delimiter i.e &
Update :
I would like to remove &page=1 from the string, no matter in which position it is on.
how do i do this?
Instead of hacking around with regular expression you should parse the string as an url (what it is)
$string = 'index.php?properties&status=av&page=1';
$parts = parse_url($string);
$queryParams = array();
parse_str($parts['query'], $queryParams);
Now just remove the parameter
unset($queryParams['page']);
and rebuild the url
$queryString = http_build_query($queryParams);
$url = $parts['path'] . '?' . $queryString;
There are many roads that lead to Rome. I'd do it with a RegEx:
$myString = 'index.php?properties&status=av&page=1';
$myNewString = preg_replace("/\&[a-z0-9]+=[0-9]+$/i","",$myString);
if you only want the &page=1-type parameters, the last line would be
$myNewString = preg_replace("/\&page=[0-9]+/i","",$myString);
if you also want to get rid of the possibility that page is the only or first parameter:
$myNewString = preg_replace("/[\&]*page=[0-9]+/i","",$myString);
Thank you guys but i think i have found the better solution, #KingCrunch had suggested a solution i extended and converted it into function. the below function can possibly remove or unset any URI variable without any regex hacks being used. i am posting it as it might help someone.
function unset_uri_var($variable, $uri) {
$parseUri = parse_url($uri);
$arrayUri = array();
parse_str($parseUri['query'], $arrayUri);
unset($arrayUri[$variable]);
$newUri = http_build_query($arrayUri);
$newUri = $parseUri['path'].'?'.$newUri;
return $newUri;
}
now consider the following uri
index.php?properties&status=av&page=1
//To remove properties variable
$url = unset_uri_var('properties', basename($_SERVER['REQUEST_URI']));
//Outputs index.php?page=1&status=av
//To remove page variable
$url = unset_uri_var('page', basename($_SERVER['REQUEST_URI']));
//Outputs index.php?properties=&status=av
hope this helps someone. and thank you #KingKrunch for your solution :)
$pos = strrpos($_SERVER['REQUEST_URI'], '&');
$url = substr($_SERVER['REQUEST_URI'], 0, $pos - 1);
Documentation for strrpos.
Regex that works on every possible situation: /(&|(?<=\?))page=.*?(?=&|$)/. Here's example code:
$regex = '/(&|(?<=\?))page=.*?(?=&|$)/';
$urls = array(
'index.php?properties&status=av&page=1',
'index.php?properties&page=1&status=av',
'index.php?page=1',
);
foreach($urls as $url) {
echo preg_replace($regex, '', $url), "\n";
}
Output:
index.php?properties&status=av
index.php?properties&status=av
index.php?
Regex explanation:
(&|(?<=\?)) -- either match a & or a ?, but if it's a ?, don't put it in the match and just ignore it (you don't want urls like index.php&status=av)
page=.*? -- matches page=[...]
(?=&|$) -- look for a & or the end of the string ($), but don't include them for the replacement (this group helps the previous one find out exactly where to stop matching)
You could use a RegEx (as Chris suggests) but it's not the most efficient solution (lots of overhead using that engine... it's easy to do with some string parsing:
<?php
//$url="http://localhost/index.php?properties&status=av&page=1";
$base=basename($_SERVER['REQUEST_URI']);
echo "Basename yields: $base<br />";
//Find the last ampersand
$lastAmp=strrpos($base,"&");
//Filter, catch no ampersands found
$removeLast=($lastAmp===false?$base:substr($base,0,$lastAmp));
echo "Without Last Parameter: $removeLast<br />";
?>
The trick is, can you guarantee that $page will be stuck on the end? If it is - great, if it isn't... what you asked for may not always solve the problem.
Related
I have some very long URL variables. Here is one example.
http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039
Ultimately it would be nice if I could find a way to use preg_replace to simply change one variable even if in the middle of the string for instance in the string above change print=no to 'print=yes for example.
I will however settle for a preg_replace pattern match that allows me to delete ?image=XYZ_1555025022.jpg. as this is a variable the name could be anything. It will always have "?image" " at the start and end with "&"
I think one of the problems I have run into is that preg_match seems to have issues on strings with "=" contained in them .
I am completely lost here in this and all those characters make may head spin. Maybe someone can give some guidance please?
Here's a demo of how you can do some of things you want using explode, parse_str and http_build_query:
$url = 'http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039';
// split on first ?
list($path, $query_string) = explode('?', $url, 2);
// parse the query string
parse_str($query_string, $params);
// delete image param
unset($params['image']);
// change the print param
$params['print'] = 'yes';
// rebuild the query
$query_string = http_build_query($params);
// reassemble the URL
$url = $path . '?' . $query_string;
echo $url;
Output:
http://localhost/index.php?mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=yes&mode=color&printscalewidth100=&printscaleheight100=&rand=56039
Demo on 3v4l.org
You can use str_replace() or preg_replace() to get your job done, but parse_url() with parse_str() will give you more controls to modify any parameters easily by array index. Finally use http_build_query() to make your final url after modification.
<?php
$url = 'http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039';
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo "BEFORE".PHP_EOL;
print_r($query);
$query['print'] = 'yes';
echo "AFTER".PHP_EOL;
print_r($query);
?>
DEMO: https://3v4l.org/npGij
Hi I have this url where i want to grab the last word (oath2_access_token) after the equals sign by PHP where the last word can be anything not just oath2_acc..
https://api.linkedin.com/v1/peoplesearch:(facets:(code,buckets:(code,name,count)))?facets=industry,network&facet=industry,12&facet=network,F&oauth2_access_token=oath2_access_token
Please help to grab the word or atleast provide me the resources where i could learn and do it myself.
Thanks.
You can use explode to get all the values after the equal signs and then just get the last element of the array:
<?php
$url = 'https://api.linkedin.com/v1/peoplesearch:(facets:(code,buckets:(code,name,count)))?facets=industry,network&facet=industry,12&facet=network,F&oauth2_access_token=oath2_access_token';
$array = explode('=', $url);
$value = end(array_values($array));
echo $value;
?>
GET
(As others have pointed out) I'm not sure why you can't simply use this...
$token = $_GET['oauth2_access_token'];
http://php.net/_get
Regex
Seeing as you have tagged this question with regex...
preg_match('/.*=(.*)/', $url, $matches);
$token = $matches[1];
.*= => Select everything up to and including the last = sign (because * is greedy)
(.*) => Select everything after the last = sign and capture it
http://php.net/preg_match
http://www.regular-expressions.info/
Explode
You could also split the url on the = sign and take the last index...
$url_array = explode('=', $url);
$token = end($url_array);
http://php.net/explode
http://php.net/end
preg_match("/oauth2_access_token\=([a-z0-9_\-]+)/i", $url, $matches);
I guess this pattern should cover the token, if not you'll need to define the allowed characters between the [] brackets.
Dump $matches to see which index grabs the token.
Either use
$_GET['oauth2_access_token']
or use parse_url. :
<?php
$url = "https://api.linkedin.com/v1/peoplesearch:(facets:(code,buckets:(code,name,count)))?facets=industry,network&facet=industry,12&facet=network,F&oauth2_access_token=oath2_access_token";
$querystring_params = array();
parse_str(parse_url($url, PHP_URL_QUERY), $querystring_params);
echo $querystring_params["oauth2_access_token"];
?>
I'm trying to do some string matching in PHP. I have the following url string in a variable:
phones/gift.nintendo-3ds/handset.blackberry-9790.html
I want remove the /gift.nintendo-3ds from the above, but the gift will always be different.
Any ideas? I want the url variable to look like this after each call different gifts:
phones/handset.blackberry-9790.html
Thanks
preg_replace('/\/gift\.[^/]*/', '', $url);
Matches /gift. then anything till the next slash and replaces it with blank.
Try with:
$input = 'phones/gift.nintendo-3ds/handset.blackberry-9790.html';
$output = preg_replace('(gift\.[^/]*\/)', '', $input);
You could split it apart, remove the second part you do not want to keep and then concat it again:
$parts = explode('/', $url, 3);
unset($parts[1]);
$result = implode('/', $parts);
This is not using any regular expression as you might have thought about but probably tells you about some other useful functions.
Demo: http://codepad.org/a1pNW8J6
A regex variant could be:
echo preg_replace('~^([^/]+)(/[^/]+)~', '$1', $url);
Demo: http://codepad.org/vyR04xMn
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'm trying to grab the 12345 out of the following URL using preg_match.
$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html";
$beg = "http://www.somesite.com/directory/";
$close = "\-";
preg_match("($beg(.*)$close)", $url, $matches);
I have tried multiple combinations of . * ? \b
Does anyone know how to extract 12345 out of the URL with preg_match?
Two things, first off, you need preg_quote and you also need delimiters. Using your construction method:
$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html";
$beg = preg_quote("http://www.somesite.com/directory/", '/');
$close = preg_quote("-", '/');
preg_match("/($beg(.*?)$close)/", $url, $matches);
But, I would write the query slightly differently:
preg_match('/directory\/(\d+)-/i', $url, $match);
It only matches the directory part, is far more readable, and ensures that you only get digits back (no strings)
This doesn't use preg_match but would achieve the same thing and would execute faster:
$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html";
$url_segments = explode("/", $url);
$last_segment = array_pop($url_segments);
list($id) = explode("-", $last_segment);
echo $id; // Prints 12345
Too slow, I am ^^.
Well, if you are not stuck on preg_match, here is a fast and readable alternative:
$num = (int)substr($url, strlen($beg));
(looking at your code I guessed, that the number you are looking for is a numeric id is it is typical for urls looking like that and will not be "12abc" or anything else.)