PHP function to remove key from a query string - php

I have a query string, like:
n1=v1&n2=v2&n3=v3
etc
I just want a php function that will accept the query string and the name (key), and remove the name value pair from the querystring.
Every example I have found uses regexes and assumes that the value will exist and that it will not be empty, but in my case (and possibly in general, I would like to know) this would also be a valid query:
n1=v1&n2=&n3
I don’t know in advance how many keys there will be.
I am convinced that regexes are monsters that eat time. Eventually all matter in the universe will end up in a regex.

parse_str('n1=v1&n2=&n3', $gets);
unset($gets['n3']);
echo http_build_query($gets);
NOTE: unset($gets['n3']); is just a show-case example

function stripkey($input, $key) {
$parts= explode("&", $input);
foreach($parts as $k=>$part) {
if(strpos($part, "=") !== false) {
$parts2= explode("=", $part);
if($key == $parts2[0]){
unset($parts[$k]);
}
}
}
return join("&", $parts);
}

Related

Script help string in php

How to make a php script that takes a argument and escapes a quote mark in every string it finds, no matter how many levels of nested array are there.
I tried something like this
$FileName = preg_replace("/'/", '', $UserInput);
but i donot want to replace the string
function recAddslashes($var){
return is_array($var) ? array_map(__FUNCTION__, $var) : addcslashes($var, "'");
}
(see addcslashes)
Not tested, but should do the trick:
function escape_single_quotes( $arg ){
if( is_array( $arg ) ){
foreach( $arg as &$k ){
$k = escape_single_quotes( $k );
}
}else{
$arg = str_replace("'","\'", $arg);
}
return $arg;
}
you need to create a recursive function that loop thought each array and is the its not an array it will replace the ' and then echo it then again loop to the next array
function traverseArray($array)
{
// Loops through each element. If element again is array, function is recalled. If not, result is echoed.
foreach($array as $key=>$value)
{
if(is_array($value))
{
traverseArray($value);
}else{
$FileName = preg_replace("/'/", '', $value);
echo $FileName;
}
}
}
If you're wanting to make the file name safe, you could employ a whitelist approach and only allow certain characters:
$Filename = preg_replace('/[^A-Za-z0-9_\-]/', '_', $userInput);
The above regex will replace any character that is not a letter, a number, a dash or an underscore. Any character that is not allowed will be replaced by an underscore. Whitelisting (allowing a small list of "safe" characters) is a much safer than blacklisting (disallowing a long list of "unsafe" characters). My first assumption is that you're allowing the user to specify the name of a file on your server. However, if you are using this approach to guard against SQL injections, then you're most definitely heading down the wrong road. Prepared Statements are the only recommended way to protect your database against SQL injections.

PHP reg_ex finding multiple words in a string

The nature of the situation, I need 1 pattern to do the following:
Create pattern that should find
exact match for single words
an exact match for a combination of 2 words.
a match of 2 words that could be found in a string.
My issue is with #3. Currently I have:
$pattern = '/\s*(foo|bar|blah|some+text|more+texted)\s*/';
How can I append to this pattern that will find "bad text" in any combination in a string.
Any ideas?
To check string for word bad use regex
/\bbad\b/
To check string for phrase bad text use regex
/\bbad text\b/
To check string for any combination of words bad and text use regex
/\b(bad|text)\s+(?!\1)(?:bad|text)\b/
To check string for presence of words bad and text use regex
/(?=.*\bbad\b)(?=.*\btext\b)/
Couple ways to do this, but here's an easy one
$array_needles = array("needle1", "needle2", etc...);
$array_found_needles = array();
$haystack = "haystack";
foreach ($array as $key=>$val) {
if(stristr($haystack, $val) {
//do whatever you want if its found
$array_found_needles[] = $val; //save the value found
}
}
$found = count($array_found_needles);
if ($found == 0) {
//do something with no needles found
} else if($found == 1) {
//do something with 1 needle found
} else if($found == 2) {
//do something with two needles found, etc
}

Temporarily remove labels/tags and re-insert them later on

Consider the following string
$input = "string with {LABELS} between brackets {HERE} and {HERE}";
I want to temporarily remove all labels (= whatever is between curly braces) so that an operation can be performed on the rest of the string:
$string = "string with between brackets and";
For arguments sake, the operation is concatenate every word that starts with 'b' with the word 'yes'.
function operate($string) {
$words = explode(' ', $string);
foreach ($words as $word) {
$output[] = (strpos($word, 0, 1) == 'b') ? "yes$word" : $word;
}
return implode(' ', $output);
}
The output of this function would be
"string with yesbetween yesbrackets and"
Now I want to insert the temporarily deleted labels back into place:
"string with {LABELS} yesbetween yesbrackets {HERE} and {HERE}"
My question is: how can I accomplish this? Important: I am not able to alter operate(), so the solution should contain a wrapper function around operate() or something. I have been thinking about this for quite a while now, but am confused as to how to do this. Could you help me out?
Edit: it would be too much to put the actual operate() in this post. It will not really add value (except make the post longer). There is not much difference between the output of operate() here and the real one. I will be able to translate any ideas from here, to the real-world situation :-)
The answer to this depends on wether or not you are able to understand operate(), even if you can't change it.
If you have absolutely no insight into operate(), your problem is simply unsolvable: To reinsert your labels you need one of
Their offset or relative position (You can't know them, if you don't know operate())
A marker for their place (You can't have them, if you don't know how operate() will work on them)
If you have at least some insight into operate(), this becomes something between solvable and easy:
If operate($a . $b)==operate($a) . operate($b), then you just split your original input by the labels, run the non-label parts through operate(), but obviously not the labels, then reassemble
If operate() is guaranteed to let a placeholder string, that itself is guaranteed to be not part of the normal input ("\0" and friends come to mind) alone, then you extract your labels in order, replace them by the placeholder, run the result through operate() and later replace the placeholder by your saved labels (in order)
Edit
After reading your comments, here are some lines of code
$input = "string with {LABELS} between brackets {HERE} and {HERE}";
//Extract labels and replace with \0
$tmp=preg_split('/(\{.*?\})/',$input,-1,PREG_SPLIT_DELIM_CAPTURE);
$labels=array();
$txt=array();
$islabel=false;
foreach ($tmp as $t) {
if ($islabel) $labels[]=$t;
else $txt[]=$t;
$islabel=!$islabel;
}
$txt=implode("\0",$txt);
//Run through operate()
$txt=operate($txt);
//Reasssemble
$txt=explode("\0",$txt);
$result='';
foreach ($txt as $t)
$result.=$t.array_shift($labels);
echo $result;
Here's what I would do as a first attempt. Split your string into single words, then feed them into operate() one by one, depending on whether the word is 'braced' or not.
$input = "string with {LABELS} between brackets {HERE} and {HERE}";
$inputArray = explode(' ',$input);
foreach($inputArray as $key => $value) {
if(!preg_match('/^{.*}$/',$value)) {
$inputArray[$key] = operate($value);
}
}
$output = implode(' ',$inputArray);

filter specific string in php

$var="UseCountry=1
UseCountryDefault=1
UseState=1
UseStateDefault=1
UseLocality=1
UseLocalityDefault=1
cantidad_productos=5
expireDays=5
apikey=ABQIAAAAFHktBEXrHnX108wOdzd3aBTupK1kJuoJNBHuh0laPBvYXhjzZxR0qkeXcGC_0Dxf4UMhkR7ZNb04dQ
distancia=15
AutoCoord=1
user_add_locality=0
SaveContactForm=0
ShowVoteRating=0
Listlayout=0
WidthThumbs=100
HeightThumbs=75
WidthImage=640
HeightImage=480
ShowImagesSystem=1
ShowOrderBy=0
ShowOrderByDefault=0
ShowOrderDefault=DESC
SimbolPrice=$
PositionPrice=0
FormatPrice=0
ShowLogoAgent=1
ShowReferenceInList=1
ShowCategoryInList=1
ShowTypeInList=1
ShowAddressInList=1
ShowContactLink=1
ShowMapLink=1
ShowAddShortListLink=1
ShowViewPropertiesAgentLink=1
ThumbsInAccordion=5
WidthThumbsAccordion=100
HeightThumbsAccordion=75
ShowFeaturesInList=1
ShowAllParentCategory=0
AmountPanel=
AmountForRegistered=5
RegisteredAutoPublish=1
AmountForAuthor=5
AmountForEditor=5
AmountForPublisher=5
AmountForManager=5
AmountForAdministrator=5
AutoPublish=1
MailAdminPublish=1
DetailLayout=0
ActivarTabs=0
ActivarDescripcion=1
ActivarDetails=1
ActivarVideo=1
ActivarPanoramica=1
ActivarContactar=1
ContactMailFormat=1
ActivarReservas=1
ActivarMapa=1
ShowImagesSystemDetail=1
WidthThumbsDetail=120
HeightThumbsDetail=90
idCountryDefault=1
idStateDefault=1
ms_country=1
ms_state=1
ms_locality=1
ms_category=1
ms_Subcategory=1
ms_type=1
ms_price=1
ms_bedrooms=1
ms_bathrooms=1
ms_parking=1
ShowTextSearch=1
minprice=
maxprice=
ms_catradius=1
idcatradius1=
idcatradius2=
ShowTotalResult=1
md_country=1
md_state=1
md_locality=1
md_category=1
md_type=1
showComments=0
useComment2=0
useComment3=0
useComment4=0
useComment5=0
AmountMonthsCalendar=3
StartYearCalendar=2009
StartMonthCalendar=1
PeriodOnlyWeeks=0
PeriodAmount=3
PeriodStartDay=1
apikey=ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ
";
in that string only i want "api==ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ";
plz guide me correctly;
EDIT
As shamittomar pointed out, the parse_str will not work for this situation, posted the proper regex below.
Given this seems to be a QUERY STRING, use the parse_str() function PHP provides.
UPDATE
If you want to do it with regex using preg_match() as powertieke pointed out:
preg_match('/apikey=(.*)/', $var, $matches);
echo $matches[1];
Should do the trick.
preg_match(); should be right up your alley
people are so fast to jump to preg match when this can be done with regular string functions thats faster.
$string = '
expireDays=5
apikey=ABQIAAAAFHktBEXrHnX108wOdzd3aBTupK1kJuoJNBHuh0laPBvYXhjzZxR0qkeXcGC_0Dxf4UMhkR7ZNb04dQ
distancia=15
AutoCoord=1';
//test to see what type of line break it is and explode by that.
$parts = (strstr($string,"\r\n") ? explode("\r\n",$string) : explode("\n",$string));
$data = array();
foreach($parts as $part)
{
$sub = explode("=",trim($part));
if(!empty($sub[0]) || !empty($sub[1]))
{
$data[$sub[0]] = $sub[1];
}
}
and use $data['apikey'] for your api key, i would also advise you to wrpa in function.
I can bet this is a better way to parse the string and much faster.
function ParsemyString($string)
{
$parts = (strstr($string,"\r\n") ? explode("\r\n",$string) : explode("\n",$string));
$data = array();
foreach($parts as $part)
{
$sub = explode("=",trim($part));
if(!empty($sub[0]) || !empty($sub[1]))
{
$data[$sub[0]] = $sub[1];
}
}
return $data;
}
$data = ParsemyString($string);
First of all, you are not looking for
api==ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ
but you are looking for
apikey=ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ
It is important to know if the api-key property always occurs at the end and if the length of the api-key value is always the same. I this is the case you could use the PHP substr() function which would be easiest.
If not you would most probably need a regular expression which you can feed to PHPs preg_match() function. Something along the lines of apikey==[a-zA-Z0-9\-] Which matches an api-key containing a-z in both lowercase and uppercase and also allows for dashes in the key. If you are using the preg_match() function you can retrieve the matches (and thus your api-key value).

stristr Case-insensitive search PHP

Please excuse my noob-iness!
I have a $string, and would like to see if it contains any one or more of a group of words, words link ct, fu, sl** ETC. So I was thinking I could do:
if(stristr("$input", "dirtyword1"))
{
$input = str_ireplace("$input", "thisWillReplaceDirtyWord");
}
elseif(stristr("$input", "dirtyWord1"))
{
$input = str_ireplace("$input", "thisWillReplaceDirtyWord2");
}
...ETC. BUT, I don't want to have to keep doing if/elseif/elseif/elseif/elseif...
Can't I just do a switch statement OR have an array, and then simply say something like?:
$dirtywords = { "f***", "c***", w****", "bit**" };
if(stristr("$input", "$dirtywords"))
{
$input = str_ireplace("$input", "thisWillReplaceDirtyWord");
}
I'd appreciate any help at all
Thank you
$dirty = array("fuc...", "pis..", "suc..");
$censored = array("f***", "p***", "s***");
$input= str_ireplace($dirty, $censored , $input);
Note, that you don't have to check stristr() to do a str_ireplace()
http://php.net/manual/en/function.str-ireplace.php
If search and replace are arrays, then str_ireplace() takes a value from each array and uses them to do search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search.
Surely not the best solution since I don't know too much PHP, but what about a loop ?
foreach (array("word1", "word2") as $word)
{
if(stristr("$input", $word))
{
$input = str_ireplace("$input", $word" "thisWillReplaceDirtyWord");
}
}
When you have several objects to test, think "loop" ;-)

Categories