How to split a search url into an associative array - php

So I would like to take a string like this,
q=Sugar Beet&qf=vegetables&range=time:[34-40]
and break it up into separate pieces that can be put into an associative array and sent to a Solr Server.
I want it to look like this
['q'] => ['Sugar Beets],
['qf'] => ['vegetables']
After using urlencode I get
q%3DSugar+Beet%26qf%3Dvegetables%26range%3Dtime%3A%5B34-40%5D
Now I was thinking I would make two separate arrays that would use preg_split() and take the information between the & and the = sign or the = and the & sign, but this leaves the problem of the final and first because they do not start with an & or end in an &.
After this, the plan was to take the two array and combine them with array_combine().
So, how could I do a preg_split that addresses the problem of the first and final entry of the string? Is this way of doing it going to be too demanding on the server? Thank you for any help.
PS: I am using Drupal ApacheSolr to do this, which is why I need to split these up. They need to be sent to an object that is going to build q and qf differently for instance.

You don't need a regular expression to parse query strings. PHP already has a built-in function that does exactly this. Use parse_str():
$str = 'q=Sugar Beet&qf=vegetables&range=time:[34-40]';
parse_str($str, $params);
print_r($params);
Produces the output:
Array
(
[q] => Sugar Beet
[qf] => vegetables
[range] => time:[34-40]
)

You could use the parse_url() function/.

also:
parse_str($_SERVER['QUERY_STRING'], $params);

Related

Is there a possible way to use multidimensional arrays to replace words in a string using str_replace() and the array() function?

Note: I have seen this question here, but my array is completely different.
Hello everyone. I have been trying to make a censoring program for my website. What I ended up with was:
$wordsList = [
array("frog","sock"),
array("Nock","crock"),
];
$message = str_replace($wordsList[0], $wordsList[1], "frog frog Nock Nock");
echo $message;
What I am trying to do is replace "frog" with "sock" using multidimentional arrays without typing all of the words out in str_replace();
Expected Output: "sock sock crocs crocs"
However, when I execute it, for some unknown reason it doesn't actually replace the words, without any errors. I think it's a rookie mistake that I made, but I have searched and have not found any documentation on using a system like this. Please help!
You need to change the structure of your wordsList array.
There are two structures that will make it easy:
As key/value pairs
This would be my recommendation since it's super clear what the strings and their replacements are.
// Store them as key/value pairs with the search and replacement strings
$wordsList = [
'frog' => 'sock',
'Nock' => 'crock',
];
$message = str_replace(
array_keys($wordsList), // Get all keys as the search array
$wordsList, // The replacements
"frog frog Nock Nock"
);
Demo: https://3v4l.org/WsUdn
As a multidimensional array
This one requires you to add the search/replacement values in the same order, which can be hard to read when you have a few different strings.
$wordsList = [
['frog', 'Nock'], // All search strings
['sock', 'crock'], // All replacements
];
$message = str_replace(
$wordsList[0], // All search strings
$wordsList[1], // The replacements strings
"frog frog Nock Nock"
);
Demo: https://3v4l.org/RQjC6
If you can't change the original array, then create a new array with the correct structure since that won't work "as is".

Separate array into comma separate strings

I want to separate my array into separate strings that all end with a comma.
Array ( [0] => 233d3f9b-3e8e-4e16-ade2-6c165a0324c6
[2] => a6c736b0-f3d2-4907-9d36-6b31adeec2d1
[3] => 1e693cba-d0ce-4a24-bd75-b834e3f44272
)
The purpose of this is so i can pass it to an API. Like this
'optionUuids' => array(
$options2,
),
The option UUidds can contain multiple values as long its separated by a comma in the end.
I tried solving my problem using implode. Implode adds a comma at the end of each line, but it treats this comma as a string. I want to have multiple option UUids so i would need commas that are actually commas and not strings.
Im having trouble explaining this. This is what i expect:
'optionUuids' => array(
233d3f9b-3e8e-4e16-ade2-6c165a0324c6,
a6c736b0-f3d2-4907-9d36-6b31adeec2d1,
1e693cba-d0ce-4a24-bd75-b834e3f44272,
),
You should use
'optionUuids' => array_values(
$options2
),
This will give you all the values but with indices starting from zero
I think, what you want to achieve is not possible
You want to change something like this
["A","B","C"]
into something like this
"A","B","C"
With JS you could do things like this
// JavaScript
arr = [1,2,3]
opt = Array(...arr)
console.log(opt)
But this has no meaning in PHP (in fact it has a meaning, but this would not help you here.) What you would need is a sort of a spread operator like in JavaScript
Unfortunately the spread operator in PHP doesn't work this way. It knows the ... operator, but this is only used in function parameter declarations and function calls. #See https://secure.php.net/manual/en/functions.arguments.php#functions.variable-arg-list

Replace multiple values in a variable

I'm looking forward a solution to replace multiple values from one of my variable ($type)
This variable can have 34 values (strings).
I would like to find a way to create a new variable ($newtype) containing new strings from the replacement of my $type.
I think using str replace would be a good solution, but the only way I see things is creating a big "If ..." (34 times?) but does not seem the best way..
Thanks in advance for you help.
Best regards.
I would advise against storing a string on multiple values in a variable as it will just get messy!
Store variables in an array in the following way
$type['value1'] = 'cheese';
$type['value2'] = 'ham';
Then if you need to change it you can just do
$type['value2'] = 'chicken';
and you will get (if using print_r)
Array
(
[value1] => cheese
[value2] => chicken
}
This means all your values will be neatly stored next to a relevant key and be easily accessable as part of an individual request
echo $type['value1']
which will echo out
Cheese
You can use preg_replace with arrays:
$from[0]='from1';
$from[1]='from2';
$from[2]='from3';
$to[0]='to1';
$to[1]='to2';
$to[2]='to3';
$newtype=preg_replace($from, $to, $type);
I have never used it like this but the documentation says that you need to use ksort to correctly match the order of the replaces:
$from[0]='from1';
$from[1]='from2';
$from[2]='from3';
$to[0]='to1';
$to[1]='to2';
$to[2]='to3';
ksort($to);
ksort($from);
$newtype=preg_replace($from, $to, $type);

preg_match from URL string

I have a string passed through a campaign source that looks like this:
/?source=SEARCH%20&utm_source=google&utm_medium=cpc&utm_term=<keyword/>&utm_content={creative}&utm_campaign=<campaign/>&cpao=111&cpca=<campaign/>&cpag=<group/>&kw=<mpl/>
when its present I need to cut this up and pass it through to our form handler so we can track our campaigns. I can check for it, hold its contents in a cookie and pass it throughout our site but i am having and issue using preg_match to cut this up and put it into variables so I can pass their values to the handler. I want the end product to look like:
$utm_source=google;
$utm_medium=cpc;
$utm_term=<keyword/>
there is no set number of characters, it could be Google, Bing etc, so i am trying to use preg_match to get the first part (utm_source) and stop past what I want (&) and so forth but I don't understand preg_match well enough to do this.
PHP should be parsing your query sting for you, into $_GET. Otherwise, PHP knows how to parse query strings. Don't use regular expressions or for this, use parse_str.
Input:
<?php
$str = "/?source=SEARCH%20&utm_source=google&utm_medium=cpc&utm_term=<keyword/>&utm_content={creative}&utm_campaign=<campaign/>&cpao=111&cpca=<campaign/>&cpag=<group/>&kw=<mpl/>";
$ar = array();
parse_str($str, $ar);
print_r($ar);
Output:
Array
(
[/?source] => SEARCH
[utm_source] => google
[utm_medium] => cpc
[utm_term] => <keyword/>
[utm_content] => {creative}
[utm_campaign] => <campaign/>
[cpao] => 111
[cpca] => <campaign/>
[cpag] => <group/>
[kw] => <mpl/>
)

Php regexp get the strings from array print_r like string

Im trying to list out here how to match strings that looks like array printr.
variable_data[0][var_name]
I would like to get from above example 3 strings, variable_data, 0 and var_name.
That above example is saved in DB so i same structure of array could be recreated but im stuck. Also a if case should look up IF the string (as above) is in that structure, otherwise no preg_match is needed.
Note: i dont want to serialize that array since the array 'may' contain some characters that might break it when unserializing and i also need that value in the array to be fully visible.
Any one with regexp skills who might know the approach ?
Solution:
(\b([\w]*[\w]).\b([\w]*[\w]).+(\b[\w]*[\w]))
Thos 2 first indexes should be skipped... but i still get what i want :)
Not for nothing but couldn't you just do..
$result = explode('[', someString);
foreach ($result as $i => $v) {
$temp = str_replace(']'. ''. $result[$i]);
//Do something with temp
}
Obviously you need to edit the above a little bit depending on what you are doing but it is very simple and even gives you the same flexibility and you don't need to invoke the matching engine...
I don't think we build regex's here for people... instead please see http://regexpal.com/ for a Regex tester / builder with visual aid.
Furthermore people usually don't know how to use them properly which is then fostered by others creating the expressions for them.
Please remember complex expressions can have terrible performance overheads although there is nothing seemingly complex about your request...
Then after it is compelte post your completed RegEx and answer your own question for maximum 1337ne$$ :)
But since I am nice here is your reward:
\[.+\]\[\d+\]
or
[a-z]+_[a-z]+\[.+\]\[\d+\]
Depending on what you want to match out of the string (which you didn't specify) so I assumed all
Both perform as follows:
arr_var[name][0]; //Matched
arr_var[name]; //Not matched
arr_var[name][0][1];//Matched
arr_var[name][2220][11];//Matched
Again, test them and understand with visual aid at the above link.
Solution:
(\b([\w]*[\w]).\b([\w]*[\w]).+(\b[\w]*[\w]))
Those 2 first indexes should be skipped... but i still get what i want :)
Edit
Here is improved one:
$str = "variable[group1][parent][child][grandchild]";
preg_match_all('/(\b([\w]*[\w]))/', $str,$matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
// Output
Array
(
[0] => variable
[1] => group1
[2] => parent
[3] => child
[4] => grandchild
)

Categories