I have many links with parameter number - value is numbers between 1-1000
http://mysite.com?one=2&two=4&number=2
http://mysite.com?one=2&two=4&four=4&number=124
http://mysite.com?one=2&three=4&number=9
http://mysite.com?two=4&number=242
http://mysite.com?one=2&two=4&number=52
How can i remove from this parameter and value with PHP? I would like receive:
http://mysite.com?one=2&two=4
http://mysite.com?one=2&two=4&four=4
http://mysite.com?one=2&three=4
http://mysite.com?two=4
http://mysite.com?one=2&two=4
Try this:
$str = 'http://mysite.com?one=2&two=4&number=2';
$url = parse_url($str);
parse_str($url['query'], $now );
unset($now['number']);
foreach($now as $key=>$value) :
if(is_bool($value) ){
$now[$key] = ($value) ? 'true' : 'false';
}
endforeach;
$options_string=http_build_query($now);
echo $url = 'http://mysite.com?'.$options_string;
Reference : PHP function to build query string from array - not http build query
Like this
$urls = '
http://mysite.com?one=2&two=4&number=2
http://mysite.com?one=2&two=4&four=4&number=124
http://mysite.com?one=2&three=4&number=9
http://mysite.com?two=4&number=242
http://mysite.com?one=2&two=4&number=52
';
echo '<pre>';
echo preg_replace('#&number=\d+#', '', $urls);
you can build a redirection after building a new URL with $_GET['one']
Use bellow steps,this is clear aproach
1- Parse the url into an array with parse_url()
2- Extract the query portion, decompose that into an array
3- Delete the query parameters you want by unset() them from the array
4- Rebuild the original url using http_build_query()
hope this help you
You could use parse_str() which parses the string into variables. In that way you can separate them easily
I wrote example of code.
<?php
$arr = array();
$arr[] = 'http://mysite.com?one=2&two=4&number=2';
$arr[] = 'http://mysite.com?one=2&two=4&four=4&number=124';
$arr[] = 'http://mysite.com?one=2&three=4&number=9';
$arr[] = 'http://mysite.com?two=4&number=242';
$arr[] = 'http://mysite.com?one=2&two=4&number=52';
function remove_invalid_arguments(array $array_invalid, $urlString)
{
$info = array();
parse_str($urlString, $info);
foreach($array_invalid as $inv)
if(array_key_exists($inv,$info)) unset($info[$inv]);
$ret = "";
$i = 0;
foreach($info as $k=>$v)
$ret .= ($i++ ? "&" : ""). "$k=$v"; //maybe urlencode also :)
return $ret;
}
//usage
$invalid = array('number'); //array of forbidden params
foreach($arr as $k=>&$v) $v =remove_invalid_arguments($invalid, $arr[1]);
print_r($arr);
?>
Working DEMO
If "&number=" is ALWAYS after the important parameters, I'd use str_split (or explode).
The more sure way is to use parse_url(),parse_str() and http_build_query() to break the URLs down and put them back together.
As per example of your url -
$s='http://mysite.com?one=2&two=4&number=2&number2=200';
$temp =explode('&',$s);
array_pop($temp);
echo $newurl = implode("&", $last);
Output is :http://mysite.com?one=2&two=4&number=2
Have a look at this one using regex: (as an alternative, preferably use a parser)
(.+?)(?:&number=\d+)
Assuming &number=2 is the last parameter. This regex will keep the whole url except the last parameter number
Related
my code :
$read = $this->m_crud->read_data("subscribe","*");
$newData=array();
foreach($read as $key){
$newData[] = $key["email"];
}
$to = implode(",",$newData);
echo json_encode($to)
result :
"test1#gmail.com, test2#gmail.com"
question : how to make the results look like this:
"test1#gmail.com", "test2#gmail.com"
Just remove the implode() Function.The implode() is a builtin function in PHP and is used to join the elements of an array. The separator (,) parameter of implode() is recommended to always use two parameters for backwards compatibility.
<?php
$read = $this->m_crud->read_data("subscribe","*");
$newData=array();
foreach($read as $key){
$newData[] = $key["email"];
}
echo json_encode($newData);
?>
I have a url like this
url:- url.php?gender=male&&grand=brand1&&id=$id
eg. $id may be 1, 100 ,23, 1000 any number
I am getting the url using
<?php echo $_SERVER['REQUEST_URI']; ?>
Is it possible to change the id and make the url like
url:- url.php?gender=gender&&brand=brand1&&id=$newId
where $newId can be any number except the one that is present in the url
function remove_querystring_var($url, $key) {
$url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
$url = substr($url, 0, -2);
return $url;
}
this will do the job, pass your url and key you want to remove in this function
ex remove_querystring_var("url.php?gender=male&&grand=brand1&&id=$id","id"), it will remove id from your url
Get the id position and the remove the id using sub string.
$url = $_SERVER['REQUEST_URI'];
#Get id position and remove && by subtracting 2 from length
$pos = strrpos($url,'id') - 2;
$url = substr($url, 0, $Pos);
echo $url;
You could use $_SERVER['QUERY_STRING'] instead.
Moreover, if your 'id' value is not always at the end, getting a substr up to it wouldn't be very robust. Instead turn it into an associative array and fiddle with it.
For example, starting with /url.php?gender=male&grand=brand1&id=999&something=else
parse_str($_SERVER['QUERY_STRING'], $parsed);
unset($parsed['id']);
// there may be a better way to do this bit.
$new_args = [];
foreach($parsed as $key=>$val){
$new_args[] = "$key=$val";
}
$new_arg_str = join($new_args, '&');
$self = $_SERVER['PHP_SELF'];
$new_endpoint = "$self?$new_arg_str";
echo $new_endpoint;
result: /url.php?gender=male&grand=brand1&something=else
Bit more legible than regex as well.
Bear in mind if you're going to redirect (using header("Location: whatever") or otherwise), you'll need to be wary of redirect loops. An if statement could avoid that.
References:
http://php.net/manual/en/reserved.variables.server.php
http://php.net/manual/en/function.parse-str.php
http://php.net/manual/en/function.unset.php
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.join.php
Here is an example of what I am trying to accomplish:
$array['aaa']['bbb']['ccc'] = "value";
$subarray = "['bbb']['ccc']";
echo $array['aaa']$subarray; // these 2 echos should be the same
echo $array['aaa']['bbb']['ccc']; // these 2 echos should be the same
It should display the same as $array['aaa']['bbb']['ccc'] i.e., "value".
This doesnt work, of course. But is there some simple solution to this?
There could be some function and the $subarrayvalue may be used as a parametr and/or as an array itself like: $subarray = array('bbb','ccc'); I dont mind as long as it worsk.
You could try something like below.
$subarray = "['bbb']['ccc']";
$temp = parse_str("\$array['aaa']".$subarray);
echo $temp;
OR To ignore single quotes -
$subarray = "[\'bbb\'][\'ccc\']";
$temp = parse_str("\$array[\'aaa\']".$subarray);
echo $temp;
Also you may refer - http://php.net/manual/en/function.parse-str.php
Just try using array chunk function http://php.net/manual/en/function.array-chunk.php
here is what actually works!!
$array['aaa']['bbb']['ccc'] = "value";
$subarray = "['bbb']['ccc']";
$string = 'echo $array[\'aaa\']' . $subarray . ';';
eval($string);
We are trying to get certain parts of a String.
We have the string:
location:32:DaD+LoC:102AD:Ammount:294
And we would like to put the information in different strings. For example $location=32 and $Dad+Loc=102AD
The values vary per string but it will always have this construction:
location:{number}:DaD+LoC:{code}:Ammount:{number}
So... how do we get those values?
That would produce what you want, but for example $dad+Loc is an invalid variable name in PHP so it wont work the way you want it, better work with an array or an stdClass Object instead of single variables.
$string = "location:32:DaD+LoC:102AD:Ammount:294";
$stringParts = explode(":",$string);
$variableHolder = array();
for($i = 0;$i <= count($stringParts);$i = $i+2){
${$stringParts[$i]} = $stringParts[$i+1];
}
var_dump($location,$DaD+LoC,$Ammount);
Easy fast forward approach:
$string = "location:32:DaD+LoC:102AD:Ammount:294";
$arr = explode(":",$string);
$location= $arr[1];
$DaD_LoC= $arr[3];
$Ammount= $arr[5];
$StringArray = explode ( ":" , $string)
By using preg_split and mapping the resulting array into an associative one.
Like this:
$str = 'location:32:DaD+LoC:102AD:Ammount:294';
$list = preg_split('/:/', $str);
$result = array();
for ($i = 0; $i < sizeof($list); $i = $i+2) {
$result[$array[$i]] = $array[$i+1];
};
print_r($result);
it seems nobody can do it properly
$string = "location:32:DaD+LoC:102AD:Ammount:294";
list(,$location,, $dadloc,,$amount) = explode(':', $string);
the php function split is deprecated so instead of this it is recommended to use preg_split or explode.
very useful in this case is the function list():
list($location, $Dad_Loc, $ammount) = explode(':', $string);
EDIT:
my code has an error:
list(,$location,, $Dad_Loc,, $ammount) = explode(':', $string);
How can i array a string, in the format that $_POST does... kind of, well i have this kind of format coming in:
101=1&2020=2&303=3
(Incase your wondering, its the result of jQuery Sortable Serialize...
I want to run an SQL statement to update a field with the RIGHT side of the = sign, where its the left side of the equal sign? I know the SQL for this, but i wanted to put it in a format that i could use the foreach($VAR as $key=>$value) and build an sql statement from that.. as i dont know how many 101=1 there will be?
I just want to explode this in a way that $key = 101 and $value = 1
Sounds confusing ;)
Thanks so so much in advanced!!
See the parse_str function.
It's not the most intuitive function name in PHP but the function you're looking for is parse_str(). You can use it like this:
$myArray = array();
parse_str('101=1&2020=2&303=3', $myArray);
print_r($myArray);
One quick and dirty solution:
<?php
$str = "101=1&2020=2&303=3";
$VAR = array();
foreach(explode('&', $str) AS $pair)
{
list($key, $value) = each(explode('=', $pair));
$VAR[$key] = $value;
}
?>
parse_str($query_string, $array_to_hold_values);
$input = "101=1&2020=2&303=3";
$output = array();
$exp = explode('&',$input);
foreach($exp as $e){
$pair = explode("=",$e);
$output[$pair[0]] = $pair[1];
}
Explode on the & to get an array that contains [ 101=1 , 2020=2 , 303=3 ] then for each element, split on the = and push the key/value pair onto a new array.