I have an URL
http://example.com/test?xyz=27373&page=4&test=5
which I want to tranform by replacing the page=4 through page=XYZ
how can I do that with preg_replace?
Yes, you can use
$oldurl = "http://test.com/test?xyz=27373&page=4&test=5"
$newurl = preg_replace("/page=\d+/", "page=XYZ", $oldurl);
Or you can reconstruct the URL from $_GET superglobal.
Do you want to set the value of xyz to the page value? I think you might need to specify a bit more. But this is easy to modify if you dont know regex.
$url = 'http://test.com/test?xyz=27373&page=4&test=5';
$urlQuery = parseUrl($url, PHP_URL_QUERY);
parse_str($urlQuery, $queryData);
$queryData['page'] = $queryData['xyz'];
unset($queryData['xyz']);
$query = http_build_query($queryData);
$outUrl = substr_replace($url, $query, strpos($url, '?'));
$url = 'http://test.com/test?xyz=27373&page=4&test=5';
preg_match('/xyz=([^&]+)/', $url, $newpage);
$new = preg_replace('/page=([^&]+)/', $newpage[0], $url);
$new = preg_replace('/xyz=([^&]+)&/', '', $new);
This will turn
http://test.com/test?xyz=27373&page=4&test=5
into
http://test.com/test?page=27373&test=5
Forgive me if this isn't what you were looking to do, but your question isn't quite clear.
I'm sure you could do something with a regular expression. However, if the URL you've given is the one you're currently handling, you already have all the request variables in $_Request.
So, rebuild the URL, replacing the values you want to replace, and then redirect to the new URL.
Otherwise, go find a regexp tutorial.
If this is your own page (and you are currently on that page) those variables will appear in a global variable named $_GET, and you could use something like array_slice, unset or array_filter to remove the unwanted variables and regenerate the URL.
If you just have that URL as a string, then what exactly are the criteria for removing the information? Technically there's no difference between
...?xyz=27373&page=4&test=5
and
...?test=5&xyz=27373&page=4
so just removing all but the first parameter might not be what you want.
If you want to remove everything except the xyz param. Take a look at parse_url and parse_str
What exactly are you trying to do? The question is a little unclear.
$XYZ = $_GET['xyz'];
$PAGE = $_GET['page'];
?
Are wanting to replace each value with another, or replace both with one?
Related
I am trying to work out a script to log IPs from poll votes on a message board, that will only be fired off if a vote is cast in one of our polls. Edit: I'm doing this via a web beacon, because I don't have access to the poll's programming. /edit
When the script fires off, it needs to know which poll is being voted in, since there are often multiple polls that are open at the same time, and log the IP of voters in a flat file that is dedicated to that poll.
First, I grab the referring URL, which is formatted like this:
http://subdomain.sample.com/t12345,action=vote
If 'vote' is found in the referring URL, the next thing I want to do is grab that t# and turn it into a variable, so I can log info in a file named t12345.txt or 12345.txt, either-or doesn't really matter, as long as it matches the topic number of the poll.
The numbers after the /t are the only thing that should change in this URL. There are currently 5 digits here, and I don't expect this to change any time soon.
My question is: How do I grab this t# from the URL and create a variable from it?
Thank you in advance!
Check out preg_match
preg_match('|/t[0-9]{5}|', $url, $matches);
if (count($matches)) {
$t_number = $matches[0]; // "/t12345"
$number = substr($t_number, 2, strlen($t_number)); // 12345
}
Assumptions:
1) The referring url will never have the pattern t#####. (t12345.com/vote)
2) You will always have five digits. (if this changes, you can do {5,6} to match 5-6 instances
Curtis already answered, but here's a non-regex alternative:
Use parse_url on the URL to get the "path".
Use explode with a comma delimiter to get your t# as array element 0 in the result.
(optional) Use explode on element 1 of the result from 2 with a delimiter of = to get "action" in element 0 and "vote" in element 1 of this new result.
Eg.
$url = "http://subdomain.sample.com/t12345,action=vote";
$url_pieces = parse_url($url);
$path = str_replace("/","",$url_pieces["path"]);
$args = explode(',',$path);
t_number_thingy = $args[0];
Edit: added str_replace as parse_url will include slash on the path.
Non regex solution (don't know about performance) and there is probably a better way but it works.
<?php
$var = "http://subdomain.sample.com/t12345,action=vote;";
$remove = "http://subdomain.sample.com/t";
$intCount = 5;
echo substr($var, strpos($var, $remove) + strlen($remove), $intCount);
?>
phpFiddle
You dont need to use regex on this you can also use str_replace(); and basename();
Like:
<?php
$ref = "http://subdomain.sample.com/t12345,action=vote";
if(substr($ref,-4)==="vote"){
$ref = basename(str_replace(',action=vote','',$ref));
}
echo $ref; //t12345
?>
Or a one liner:
$ref = (substr($ref,-4)==="vote") ? basename(str_replace(',action=vote','',$ref)) : "Unknown";
I can't find a solution for this problem. I have this URL http://examplesite.com/?skill-type=new and I want to get the very last word after the = sign, using PHP only. "skill-type" stays the same all the time Thanks in advance :)
This snippet should do:
$url = 'http://examplesite.com/?skill-type=new';
$skillType = explode('&', parse_url($url, PHP_URL_QUERY))['skill-type'];
Check parse_url for more details.
If you meant that the request comes in to that particular url, just use $_REQUEST['skill-type'] to retrieve the value.
Considering you already have the URL in a variable, let's say
$url = 'http://examplesite.com/?skill-type=new;
One possible way (certainly there are others) would be:
$urlArray = explode('=',$url);
$last = $urlArray[sizeof($urlArray)-1];
Note:
only applicable if you don't know how the URL comes, if you do, consider on using $_GET
Use the PHP $_GET Global Variable
$skill_type = $_GET['skill-type'];
PHP will automatically parse GET variables for you. To access the value of the skill-type variable, you need only use $_GET['skill-type']. For instance:
echo $_GET['skill-type'];
Will display
new
Generate your url by $_SERVER variable and then split it like this
$url = "http://examplesite.com/?skill-type=new";
$array = explode("=", $url);
$last_word = $array[1];
Use substr (url, posstr (url,'=')+1) or if this is the page being loaded $_GET ['skill-type']
I have back_url given to me from the outside. I need to generate a hash and to make redirect to this back_url with this param: header("Location: $back_url?hash=123sdf"). But the problem is that I don't know the format of back_url.
It may be www.example.com and I do header("Location: $back_url/?hash=123sdf") sj that's fine.
It maybe www.example.com/?param=value and if I do header("Location: $back_url/?hash=123sdf") it's wrong, because it would be www.example.com/?param=value/?hash=123asd.
And so on. The question is: what's the universal way to pass params to back_url ignoring its format?
A complex but very clean way is
Use parse_url() to extract the query string (if any) from the URL into an array
Add hash to the resulting array: $params["hash"] = "1234";
Use http_build_query() to glue the parameters back into a query string
Take all the components returned by parse_url() and glue them back into a full URL
one thing to note is that this dissects the URL into it components and glues it back together, so it's likely it won't work with URLs that are broken in the first place.
Have you tried using http://php.net/manual/en/function.parse-url.php ?
If you have the PECL HTTP extension, use http_build_url:
$url = '...';
$hash = '...';
$new_url = http_build_url($url, array('hash' => $hash), HTTP_URL_JOIN_QUERY);
If you don't have http_build_url, you can use parse_url to find the different parts if a URL. Then it's just a matter of pasting them together. Here's a solution in the manual which can be tailored for your needs.
Well, you would need to detect if $back_url has other query parameters (or GET variables) and append your hash using ?hash=123asd if it hadn't, or using &hash=123asd if indeed it had query parameters.
If you know that $back_url is a full url like http://whatever.com/blah/blah (the important part being http://whatever.com, you can use parse_url to get all components, and then continue with Pekka's answer. If your $back_url doesn't begin with http://..., then prepend the right value (I assume http://$_SERVER['host'] and, again, continue with Pekka's answer.
Wrote this function:
private function addUrlParam(array $params, $url){
$parsed = parse_url($url);
if(!isset($parsed['query']))
{
$slash = '';
if(substr($url, -1) !== '/')
$slash = '/';
$start_with = $slash.'?';
}
else
$start_with = '&';
$scheme = '';
if(!isset($parsed['scheme']))
$scheme = 'http://';
$query = http_build_query($params);
return $scheme.$url.$start_with.$query;
}
Looks like it's perfect for me. Thanks everyone.
I've this url:
http://localhost/alignment/?page_id=52&q=2
I want to get the portion: ?page_id=52 , how can I do that?
$_SERVER['QUERY_STRING']
or
$url = "http://localhost/alignment/?page_id=52&q=2";
$bits = explode("?", $url);
$querystring = $bits[1]; // this is what you want
but the first one will be much more reliable and is easier. :)
EDIT
if you meant that you just wanted that one variable use:
$_GET['page_id']
This is called a query string. The main portion of the query string is separated by the rest of the URL with a ?. Each argument in the query string is separated by a &.
PHP:
$_SERVER['QUERY_STRING'];
If you want to get the individual pieces, use:
$_GET['page_id']; //etc...
You can get the whole query string with $_SERVER['QUERY_STRING'], but you would have to parse out page_id part. If you insist on doing things manually the function parse_str may come in handy.
A better choice would be to just use the predefined $_GET global variable. $_GET['page_id'] would give you value 52.
If you have it as a string, use parse_url. Documentation here. Get the query value of it. or if its current request use $_SERVER['QUERY_STRING']
echo parse_url($url,PHP_URL_QUERY);
This should do it:
echo $_SERVER['QUERY_STRING'];
Assign the url to string and then explode() it,
http://php.net/manual/en/function.explode.php, using the ? as a delimiter
How can I make a link that justs adds or changes 1 GET var while maintaining all others?
I have a page that is created using different GET vars.
So it will be like mypage.php?color=red&size=7&brand=some%20brand
So I want to have a link that sets it to page=2 or size=8. Whats the easiest way to have a link do that without reseting all the other vars?
I hope that makes sense, let me know if I need to further explain anything
You can parse the url with parse_str to get the values of the url. You can then build a http query by using http_build_query:
$query_arr = $_GET; //or parse_str($_SERVER['QUERY_STRING'], $query_arr)
$query_arr["page"] = 2;
$query_arr["size"] = 8;
$query = http_build_query($query_arr);
EDIT: Sorry I mixed up the two functions ... its parse_str() of course.
http_build_query