PHP Url string to array - php

I'm trying to find out if there's any function that would split a string like:
keyword=flower|type=outdoors|colour=red
to array:
array('keyword' => 'flower', 'type' => 'outdoors', 'colour' => 'red')
At the moment I built a custom function, which uses explode to first split elements with the separator | and then each of those with assignment symbol =, but is there perhaps a native function which would do it out of the box by specifying the string separator?
The function I've written looks like this:
public static function splitStringToArray(
$string = null,
$itemDivider = '|',
$keyValueDivider = '='
) {
if (empty($string)) {
return array();
}
$items = explode($itemDivider, $string);
if (empty($items)) {
return array();
}
$out = array();
foreach($items as $item) {
$itemArray = explode($keyValueDivider, $item);
if (
count($itemArray) > 1 &&
!empty($itemArray[1])
) {
$out[$itemArray[0]] = $itemArray[1];
}
}
return $out;
}

$string = "keyword=flower|type=outdoors|colour=red";
$string = str_replace('|', '&', $string);
parse_str($string, $values);
$values=array_filter($values); // Remove empty pairs as per your comment
print_r($values);
Output
Array
(
[keyword] => flower
[type] => outdoors
[colour] => red
)
Fiddle

Use regexp to solve this problem.
([^=]+)\=([^\|]+)
http://regex101.com/r/eQ9tW8/1

The issue is that your chosen format of representing variables in a string is non-standard. If you are able to change the | delimiter to a & character you would have (what looks like) a query string from a URL - and you'll be able to parse that easily:
$string = "keyword=flower&type=outdoors&colour=red";
parse_str( $string, $arr );
var_dump( $arr );
// array(3) { ["keyword"]=> string(6) "flower" ["type"]=> string(8) "outdoors" ["colour"]=> string(3) "red" }
I would recommend changing the delimiter at the source instead of manually replacing it with replace() or something similar (if possible).

Related

how to get POST parameters from URL in PHP [duplicate]

How can I turn a string below into an array?
pg_id=2&parent_id=2&document&video
This is the array I am looking for,
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.
$get_string = "pg_id=2&parent_id=2&document&video";
parse_str($get_string, $get_array);
print_r($get_array);
Sometimes parse_str() alone is note accurate, it could display for example:
$url = "somepage?id=123&lang=gr&size=300";
parse_str() would return:
Array (
[somepage?id] => 123
[lang] => gr
[size] => 300
)
It would be better to combine parse_str() with parse_url() like so:
$url = "somepage?id=123&lang=gr&size=300";
parse_str( parse_url( $url, PHP_URL_QUERY), $array );
print_r( $array );
Using parse_str().
$str = 'pg_id=2&parent_id=2&document&video';
parse_str($str, $arr);
print_r($arr);
If you're having a problem converting a query string to an array because of encoded ampersands
&
then be sure to use html_entity_decode
Example:
// Input string //
$input = 'pg_id=2&parent_id=2&document&video';
// Parse //
parse_str(html_entity_decode($input), $out);
// Output of $out //
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
Use http://us1.php.net/parse_str
Attention, its usage is:
parse_str($str, &$array);
not
$array = parse_str($str);
Please note that the above only applies to PHP version 5.3 and earlier. Call-time pass-by-reference has been removed in PHP 5.4.
There are several possible methods, but for you, there is already a built-in parse_str function:
$array = array();
parse_str($string, $array);
var_dump($array);
This is a one-liner for parsing a query from the current URL into an array:
parse_str($_SERVER['QUERY_STRING'], $query);
You can try this code:
<?php
$str = "pg_id=2&parent_id=2&document&video";
$array = array();
parse_str($str, $array);
print_r($array);
?>
Output:
Array
(
[pg_id] => 2
[parent_id] => 2
[document] =>
[video] =>
)
You can use the PHP string function parse_str() followed by foreach loop.
$str="pg_id=2&parent_id=2&document&video";
parse_str($str,$my_arr);
foreach($my_arr as $key=>$value){
echo "$key => $value<br>";
}
print_r($my_arr);
But PHP already comes with a built in $_GET function. this will convert it to the array by itself.
try print_r($_GET) and you will get the same results.
This is the PHP code to split a query in MySQL and SQL Server:
function splitquery($strquery)
{
$arrquery = explode('select', $strquery);
$stry = ''; $strx = '';
for($i=0; $i<count($arrquery); $i++)
{
if($i == 1)
{
echo 'select ' . trim($arrquery[$i]);
}
elseif($i > 1)
{
$strx = trim($arrquery[($i-1)]);
if(trim(substr($strx,-1)) != '(')
{
$stry = $stry . '
select ' . trim($arrquery[$i]);
}
else
{
$stry = $stry.trim('select ' . trim($arrquery[$i]));
}
$strx = '';
}
}
return $stry;
}
Example:
Query before
Select xx from xx select xx,(select xx) from xx where y=' cc'
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc";
Query after
select xx from xx
select xx,(select xx) from xx where y=' cc'
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc
For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra "e"—in the URL the function will silently fail without an error or exception being thrown:
a=2&b=2&c=5&d=4&e=1&e=2&e=3
So I prefer using my own parser like so:
//$_SERVER['QUERY_STRING'] = `a=2&b=2&c=5&d=4&e=100&e=200&e=300`
$url_qry_str = explode('&', $_SERVER['QUERY_STRING']);
//arrays that will hold the values from the url
$a_arr = $b_arr = $c_arr = $d_arr = $e_arr = array();
foreach( $url_qry_str as $param )
{
$var = explode('=', $param, 2);
if($var[0]=="a") $a_arr[]=$var[1];
if($var[0]=="b") $b_arr[]=$var[1];
if($var[0]=="c") $c_arr[]=$var[1];
if($var[0]=="d") $d_arr[]=$var[1];
if($var[0]=="e") $e_arr[]=$var[1];
}
var_dump($e_arr);
// will return :
//array(3) { [0]=> string(1) "100" [1]=> string(1) "200" [2]=> string(1) "300" }
Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.
Hope that helps!

Make array from String [duplicate]

How can I turn a string below into an array?
pg_id=2&parent_id=2&document&video
This is the array I am looking for,
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.
$get_string = "pg_id=2&parent_id=2&document&video";
parse_str($get_string, $get_array);
print_r($get_array);
Sometimes parse_str() alone is note accurate, it could display for example:
$url = "somepage?id=123&lang=gr&size=300";
parse_str() would return:
Array (
[somepage?id] => 123
[lang] => gr
[size] => 300
)
It would be better to combine parse_str() with parse_url() like so:
$url = "somepage?id=123&lang=gr&size=300";
parse_str( parse_url( $url, PHP_URL_QUERY), $array );
print_r( $array );
Using parse_str().
$str = 'pg_id=2&parent_id=2&document&video';
parse_str($str, $arr);
print_r($arr);
If you're having a problem converting a query string to an array because of encoded ampersands
&
then be sure to use html_entity_decode
Example:
// Input string //
$input = 'pg_id=2&parent_id=2&document&video';
// Parse //
parse_str(html_entity_decode($input), $out);
// Output of $out //
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
Use http://us1.php.net/parse_str
Attention, its usage is:
parse_str($str, &$array);
not
$array = parse_str($str);
Please note that the above only applies to PHP version 5.3 and earlier. Call-time pass-by-reference has been removed in PHP 5.4.
There are several possible methods, but for you, there is already a built-in parse_str function:
$array = array();
parse_str($string, $array);
var_dump($array);
This is a one-liner for parsing a query from the current URL into an array:
parse_str($_SERVER['QUERY_STRING'], $query);
You can try this code:
<?php
$str = "pg_id=2&parent_id=2&document&video";
$array = array();
parse_str($str, $array);
print_r($array);
?>
Output:
Array
(
[pg_id] => 2
[parent_id] => 2
[document] =>
[video] =>
)
You can use the PHP string function parse_str() followed by foreach loop.
$str="pg_id=2&parent_id=2&document&video";
parse_str($str,$my_arr);
foreach($my_arr as $key=>$value){
echo "$key => $value<br>";
}
print_r($my_arr);
But PHP already comes with a built in $_GET function. this will convert it to the array by itself.
try print_r($_GET) and you will get the same results.
This is the PHP code to split a query in MySQL and SQL Server:
function splitquery($strquery)
{
$arrquery = explode('select', $strquery);
$stry = ''; $strx = '';
for($i=0; $i<count($arrquery); $i++)
{
if($i == 1)
{
echo 'select ' . trim($arrquery[$i]);
}
elseif($i > 1)
{
$strx = trim($arrquery[($i-1)]);
if(trim(substr($strx,-1)) != '(')
{
$stry = $stry . '
select ' . trim($arrquery[$i]);
}
else
{
$stry = $stry.trim('select ' . trim($arrquery[$i]));
}
$strx = '';
}
}
return $stry;
}
Example:
Query before
Select xx from xx select xx,(select xx) from xx where y=' cc'
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc";
Query after
select xx from xx
select xx,(select xx) from xx where y=' cc'
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc
For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra "e"—in the URL the function will silently fail without an error or exception being thrown:
a=2&b=2&c=5&d=4&e=1&e=2&e=3
So I prefer using my own parser like so:
//$_SERVER['QUERY_STRING'] = `a=2&b=2&c=5&d=4&e=100&e=200&e=300`
$url_qry_str = explode('&', $_SERVER['QUERY_STRING']);
//arrays that will hold the values from the url
$a_arr = $b_arr = $c_arr = $d_arr = $e_arr = array();
foreach( $url_qry_str as $param )
{
$var = explode('=', $param, 2);
if($var[0]=="a") $a_arr[]=$var[1];
if($var[0]=="b") $b_arr[]=$var[1];
if($var[0]=="c") $c_arr[]=$var[1];
if($var[0]=="d") $d_arr[]=$var[1];
if($var[0]=="e") $e_arr[]=$var[1];
}
var_dump($e_arr);
// will return :
//array(3) { [0]=> string(1) "100" [1]=> string(1) "200" [2]=> string(1) "300" }
Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.
Hope that helps!

PHP Sophisticated String parsing

This may be able to be accomplished with a regular expression but I have no idea. What I am trying to accomplish is being able to parse a string with a given delimiter but when it sees a set of brackets it parses differently. As I am a visual learning let me show you an example of what I am attempting to achieve. (PS this is getting parsed from a url)
Given the string input:
String1,String2(data1,data2,data3),String3,String4
How can I "transform" this string into this array:
{
"String1": "String1",
"String2": [
"data1",
"data2",
"data3"
],
"String3": "String3",
"String4": "String4
}
Formatting doesn't have to be this strict as I'm just attempting to make a simple API for my project.
Obviously things like
array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )
Wouldn't work because there are commas inside the brackets as well. I've attempted manual parsing looking at each character at a time but I fear for the performance and it doesn't actually work anyway. I've pasted the gist of my attempt.
https://gist.github.com/Fudge0952/24cb4e6a4ec288a4c492
While you could try to split your initial string on commas and ignore anything in parentheses for the first split, this necessarily makes assumptions about what those string values can actually be (possibly requiring escaping/unescaping values depending on what those strings have to contain).
If you have control over the data format, though, it would be far better to just start with JSON. It's well-defined and well-supported.
You can either build an ad-hoc parser like (mostly untested):
<?php
$p = '!
[^,\(\)]+ # token: String
|, # token: comma
|\( # token: open
|\) # token: close
!x';
$input = 'String1,String2(data1,data2,data3,data4(a,b,c)),String3,String4';
preg_match_all($p, $input, $m);
// using a norewinditerator, so we can use nested foreach-loops on the same iterator
$it = new NoRewindIterator(
new ArrayIterator($m[0])
);
var_export( foo( $it ) );
function foo($tokens, $level=0) {
$result = [];
$current = null;
foreach( $tokens as $t ) {
switch($t) {
case ')':
break; // foreach loop
case '(':
if ( is_null($current) ) {
throw new Exception('moo');
}
$tokens->next();
$result[$current] = foo($tokens, $level+1);
$current = null;
break;
case ',':
if ( !is_null($current) ) {
$result[] = $current;
$current = null;
}
break;
default:
$current = $t;
break;
}
}
if ( !is_null($current) ) {
$result[] = $current;
}
return $result;
}
prints
array (
0 => 'String1',
'String2' =>
array (
0 => 'data1',
1 => 'data2',
2 => 'data3',
'data4' =>
array (
0 => 'a',
1 => 'b',
2 => 'c',
),
),
1 => 'String3',
2 => 'String4',
)
(but will most certainly fail horribly for not-well-formed strings)
or take a look at lexer/parser generator like e.g. PHP_LexerGenerator and PHP_ParserGenerator.
This is a solution with preg_match_all():
$string = 'String1,String2(data1,data2,data3),String3,String4,String5(data4,data5,data6)';
$pattern = '/([^,(]+)(\(([^)]+)\))?/';
preg_match_all( $pattern, $string, $matches );
$result = array();
foreach( $matches[1] as $key => $val )
{
if( $matches[3][$key] )
{ $add = explode( ',', $matches[3][$key] ); }
else
{ $add = $val; }
$result[$val] = $add;
}
$json = json_encode( $result );
3v4l.org demo
Pattern explanation:
([^,(]+) group 1: any chars except ‘,’ and ‘(’
(\(([^)]+)\))? group 2: zero or one occurrence of brackets wrapping:
└──┬──┘
┌──┴──┐
([^)]+) group 3: any chars except ‘,’

Parse query string into an array

How can I turn a string below into an array?
pg_id=2&parent_id=2&document&video
This is the array I am looking for,
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.
$get_string = "pg_id=2&parent_id=2&document&video";
parse_str($get_string, $get_array);
print_r($get_array);
Sometimes parse_str() alone is note accurate, it could display for example:
$url = "somepage?id=123&lang=gr&size=300";
parse_str() would return:
Array (
[somepage?id] => 123
[lang] => gr
[size] => 300
)
It would be better to combine parse_str() with parse_url() like so:
$url = "somepage?id=123&lang=gr&size=300";
parse_str( parse_url( $url, PHP_URL_QUERY), $array );
print_r( $array );
Using parse_str().
$str = 'pg_id=2&parent_id=2&document&video';
parse_str($str, $arr);
print_r($arr);
If you're having a problem converting a query string to an array because of encoded ampersands
&
then be sure to use html_entity_decode
Example:
// Input string //
$input = 'pg_id=2&parent_id=2&document&video';
// Parse //
parse_str(html_entity_decode($input), $out);
// Output of $out //
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
Use http://us1.php.net/parse_str
Attention, its usage is:
parse_str($str, &$array);
not
$array = parse_str($str);
Please note that the above only applies to PHP version 5.3 and earlier. Call-time pass-by-reference has been removed in PHP 5.4.
There are several possible methods, but for you, there is already a built-in parse_str function:
$array = array();
parse_str($string, $array);
var_dump($array);
This is a one-liner for parsing a query from the current URL into an array:
parse_str($_SERVER['QUERY_STRING'], $query);
You can try this code:
<?php
$str = "pg_id=2&parent_id=2&document&video";
$array = array();
parse_str($str, $array);
print_r($array);
?>
Output:
Array
(
[pg_id] => 2
[parent_id] => 2
[document] =>
[video] =>
)
You can use the PHP string function parse_str() followed by foreach loop.
$str="pg_id=2&parent_id=2&document&video";
parse_str($str,$my_arr);
foreach($my_arr as $key=>$value){
echo "$key => $value<br>";
}
print_r($my_arr);
But PHP already comes with a built in $_GET function. this will convert it to the array by itself.
try print_r($_GET) and you will get the same results.
This is the PHP code to split a query in MySQL and SQL Server:
function splitquery($strquery)
{
$arrquery = explode('select', $strquery);
$stry = ''; $strx = '';
for($i=0; $i<count($arrquery); $i++)
{
if($i == 1)
{
echo 'select ' . trim($arrquery[$i]);
}
elseif($i > 1)
{
$strx = trim($arrquery[($i-1)]);
if(trim(substr($strx,-1)) != '(')
{
$stry = $stry . '
select ' . trim($arrquery[$i]);
}
else
{
$stry = $stry.trim('select ' . trim($arrquery[$i]));
}
$strx = '';
}
}
return $stry;
}
Example:
Query before
Select xx from xx select xx,(select xx) from xx where y=' cc'
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc";
Query after
select xx from xx
select xx,(select xx) from xx where y=' cc'
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc
For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra "e"—in the URL the function will silently fail without an error or exception being thrown:
a=2&b=2&c=5&d=4&e=1&e=2&e=3
So I prefer using my own parser like so:
//$_SERVER['QUERY_STRING'] = `a=2&b=2&c=5&d=4&e=100&e=200&e=300`
$url_qry_str = explode('&', $_SERVER['QUERY_STRING']);
//arrays that will hold the values from the url
$a_arr = $b_arr = $c_arr = $d_arr = $e_arr = array();
foreach( $url_qry_str as $param )
{
$var = explode('=', $param, 2);
if($var[0]=="a") $a_arr[]=$var[1];
if($var[0]=="b") $b_arr[]=$var[1];
if($var[0]=="c") $c_arr[]=$var[1];
if($var[0]=="d") $d_arr[]=$var[1];
if($var[0]=="e") $e_arr[]=$var[1];
}
var_dump($e_arr);
// will return :
//array(3) { [0]=> string(1) "100" [1]=> string(1) "200" [2]=> string(1) "300" }
Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.
Hope that helps!

PHP string manipulation, inside the string

I have string:
ABCDEFGHIJK
And I have two arrays of positions in that string that I want to insert different things to.
Array
(
[0] => 0
[1] => 5
)
Array
(
[0] => 7
[1] => 9
)
Which if I decided to add the # character and the = character, it'd produce:
#ABCDE=FG#HI=JK
Is there any way I can do this without a complicated set of substr?
Also, # and = need to be variables that can be of any length, not just one character.
You can use string as array
$str = "ABCDEFGH";
$characters = preg_split('//', $str, -1);
And afterwards you array_splice to insert '#' or '=' to position given by array
Return the array back to string is done by:
$str = implode("",$str);
This works for any number of characters (I am using "#a" and "=b" as the character sequences):
function array_insert($array,$pos,$val)
{
$array2 = array_splice($array,$pos);
$array[] = $val;
$array = array_merge($array,$array2);
return $array;
}
$s = "ABCDEFGHIJK";
$arr = str_split($s);
$arr_add1 = array(0=>0, 1=>5);
$arr_add2 = array(0=>7, 1=>9);
$char1 = '#a';
$char2 = '=b';
$arr = array_insert($arr, $arr_add1[0], $char1);
$arr = array_insert($arr, $arr_add1[1] + strlen($char1), $char2);
$arr = array_insert($arr, $arr_add2[0]+ strlen($char1)+ strlen($char2), $char1);
$arr = array_insert($arr, $arr_add2[1]+ strlen($char1)+ strlen($char2) + strlen($char1), $char2);
$s = implode("", $arr);
print_r($s);
There is an easy function for that: substr_replace. But for this to work, you would have to structure you array differently (which would be more structured anyway), e.g.:
$replacement = array(
0 => '#',
5 => '=',
7 => '#',
9 => '='
);
Then sort the array by keys descending, using krsort:
krsort($replacement);
And then you just need to loop over the array:
$str = "ABCDEFGHIJK";
foreach($replacement as $position => $rep) {
$str = substr_replace($str, $rep, $position, 0);
}
echo $str; // prints #ABCDE=FG#HI=JK
This works by inserting the replacements starting from the end of string. And it would work with any replacement string without having to determine the length of that string.
Working DEMO

Categories