Grab param from string and convert to array php - php

I have input string from users. this input from users are unpredictable. it's mean user can input any string as they like.
I would like to filter the input that match following pattern and return it as an array
These following string pattern should works:
product=bag, product=tshirt, product=shoes
product=bag status=sold, product=jeans, product=shoes
product=all
I would like the output as array like below :
Array(
[0] => Array
(
[product] => bag
[status] => sold
)
[1] => Array
(
[product] => jeans
)
[2] => Array
(
[product] => shoes
)
)
I guess it can be achieved by use preg_match_all() beside explode. Anyone can give me example using preg_match_all ? or any other ways are ok for me as long as the best method.
$string = 'product=bag status=sold, product=tshirt, product=shoes';
$m = preg_match_all('/needregexrulehere/', $string, $matches);

You don't need a regular expression for this, you can do something like this:
$return = array();
foreach( str_getcsv( $string) as $line) {
parse_str( str_replace( ' ' , '&', $line), $temp);
$return[] = $temp;
}
This will output:
Array
(
[0] => Array
(
[product] => bag
[status] => sold
)
[1] => Array
(
[product] => tshirt
)
[2] => Array
(
[product] => shoes
)
)
I will leave error checking / input sanitation up to the OP.

Related

PHP - Preg Match All - Wordpress Multiple short codes with multiple parameters

I'm trying to find a regex capable of capturing the content of short codes produces in Wordpress.
My short codes have the following structure:
[shortcode name param1="value1" param2="value2" param3="value3"]
The number of parameters is variable.
I need to capture the shortcode name, the parameter name and its value.
The closest results I have achieved is with this:
/(?:\[(.*?)|\G(?!^))(?=[^][]*])\h+([^\s=]+)="([^\s"]+)"/
If I have the following content in the same string:
[specs product="test" category="body"]
[pricelist keyword="216"]
[specs product="test2" category="network"]
I get this:
0=>array(
0=>[specs product="test"
1=> category="body"
2=>[pricelist keyword="216"
3=>[specs product="test2"
4=> category="network")
1=>array(
0=>specs
1=>
2=>pricelist
3=>specs
4=>)
2=>array(
0=>product
1=>category
2=>keyword
3=>product
4=>category)
3=>array(
0=>test
1=>body
2=>216
3=>test2
4=>network)
)
I have tried different regex models but I always end up with the same issue, if I have more than one parameter, it fails to detect it.
Do you have any idea of how I could achieve this?
Thanks
Laurent
You could make use of the \G anchor using 3 capture groups, where capture group 1 is the name of the shortcode, and group 2 and 3 the key value pairs.
Then you can remove the first entry of the array, and remove the empty entries in the 1st, 2nd and 3rd entry.
This is a slightly updated pattern
(?:\[(?=[^][]*])(\w+)|\G(?!^))\h+(\w+)="([^"]+)"
Regex demo | Php demo
Example
$s = '[specs product="test" category="body"]';
$pattern = '/(?:\[(?=[^][]*])(\w+)|\G(?!^))\h+(\w+)="([^"]+)"/';
$strings = [
'[specs product="test" category="body"]',
'[pricelist keyword="216"]',
'[specs product="test2" category="network" key="value"]'
];
foreach($strings as $s) {
if (preg_match_all($pattern, $s, $matches)) {
unset($matches[0]);
$matches = array_map('array_filter', $matches);
print_r($matches);
}
}
Output
Array
(
[1] => Array
(
[0] => specs
)
[2] => Array
(
[0] => product
[1] => category
)
[3] => Array
(
[0] => test
[1] => body
)
)
Array
(
[1] => Array
(
[0] => pricelist
)
[2] => Array
(
[0] => keyword
)
[3] => Array
(
[0] => 216
)
)
Array
(
[1] => Array
(
[0] => specs
)
[2] => Array
(
[0] => product
[1] => category
[2] => key
)
[3] => Array
(
[0] => test2
[1] => network
[2] => value
)
)

How to extract certain words from a php string?

I have a long string like this I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];. Now I just want to get certain words like 'I1','I2','I8','NA1' and so on i.e. words between ':'&';' only ,and store them in array. How to do that efficiently?
I have already tried using preg_split() and it works but giving me wrong output. As shown below.
// $a is the string I want to extract words from
$str = preg_split("/[;:]/", $a);
print_r($str);
The output I am getting is this
Array
(
[0] => I8
[1] => 2
[2] => I1
[3] => 1
[4] => I2
[5] => 2
[6] => I3
[7] => 2
[8] => I4
[9] => 4
[10] =>
)
Array
(
[0] => NA1
[1] => 5
[2] =>
)
Array
(
[0] => IA1
[1] => [1,2,3,4,5]
[2] =>
)
Array
(
[0] => S1
[1] => asadada
[2] =>
)
Array
(
[0] => SA1
[1] => [1,2,3,4,5]
[2] =>
)
But I am expecting 'I8','I1','I2','I3','I4' also in seperated array with position [0]. Any help on how to do this.
You could try something like.
<?php
$str = 'I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];';
preg_match_all('/(?:^|[;:])(\w+)/', $str, $result);
print_r($result[1]); // Matches are here in $result[1]
You can perform a greedy match to match the items between ; and : using preg_match_all()
<?php
$str = 'I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];';
preg_match_all('/;(.+?)\:/',$str,$matches);
print_r($matches[1]);
Live Demo: https://3v4l.org/eBsod
One possible approach is using a combination of explode() and implode(). The result is returned as a string, but you can easily put it into an array for example.
<?php
$input = "I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];.";
$output = array();
$array = explode(";", $input);
foreach($array as $item) {
$output[] = explode(":", $item)[0];
}
echo implode(",", $output);
?>
Output:
I1,I2,I8,NA1,IA1,S1,SA1,SA1,.

Getting array values into a string

I output a PHP object via a loop but withing this look I have a few nested arrays.
[categories] => Array
(
[0] => Array
(
[0] => Chinese
[1] => chinese
)
[1] => Array
(
[0] => Vietnamese
[1] => vietnamese
)
)
[phone] => 5123355555
I can get the phone like this:
$response->businesses[$x]->phone
How do I get categories (first value) into a string like this:
Chinese, Vietnamese
You can achieve with array_column() :
$newArray = array_column($response->businesses[$x]->categories, 0);
It returns an array with the column 0. So the response will be:
print_r($newArray);
//Array ( [0] => Chinese [1] => Vietnamese )
Then you can join it safely:
$newString = implode(",", $newArray)
echo $newString; // "Chinese, Vietnamese"
implode(', ', array_map(function($item) {
return $item[0];
}, $response->businesses[$x]->categories));

preg_match_all possible variations

I like to know up to three parts of a string. The string can be either
{identifier}, {identifier:foo}, {identifier:foo|bar} or {identifier|bar}
The string can occur multiple times in $content this is why is use preg_match_all
Currently I have
preg_match_all( '#\{'.preg_quote($identifier).':?([^\}|]+)?\|?([^\}]+)?\}#i', $content, $matches );
which work for the very first all versions except {identifier|bar} but not for the others.
Edit:
$matches should look like this (with a single appearance in $content)
Array
(
[0] => Array
(
[0] => {timezone:foo|bar}
)
[1] => Array
(
[0] => foo
)
[2] => Array
(
[0] => bar
)
)

Extract The Specific parameter value from array

I have a array like this
[0] => Array
(
[0] => LBLdss_COLLEsdfCTIONS_RsdfsdEPORT_TITfsdfLE
[1] =>
[2] =>
[3] => Array
(
[Administration] => Array
(
[bidsflldsf6] => Array
(
[0] => themes/Care2012/images/Payments
[1] => LsdfBL_OPsddfD_BIsfdfsLLING_SsdfdsUMsdfMARY_TITLE
[2] => LsdfsdBL_OPDfdsfd_BILfdsLING_dsfdsSUMMARY
[3] => ./index.php?module=Rsdfepfdsforts&action=reposfdfdsrtsel&rname=Opdpasfdfypdf
)
[bilhghjgl_pat_reg] => Array
(
[0] => themsdfsdes/Casfdfre2aasd012/imasdfges/Pasdymesddfnts
[1] => LBL_sdfsPAT_RsdfEG_TsdfITLE
[2] => LBL_PdfsdAT_sfdREG_TdsfdITLE_DsdfsETAIL
[3] => ./index.php?module=Rexcvpofdsrts&action=reportsel&rname=Pacxvtregcollxcvectionpdf
)
)
)
[4] =>
)
Now i need to extract value of rname from this index [3] => ./index.php?module=Rexcvpofdsrts&action=reportsel&rname=Pacxvtregcollxcvectionpdf (which is Pacxvtregcollxcvectionpdf in this case)and have to save it
I can try explode function but it is heavy for me since my array size is large
please help in resolving this
Thanks
Try placing a foreach for ciclying the array and formulate a regular expression for extract your param. Like this:
foreach($youvar as $text) {
preg_match('$rname=(.+?)$', $text, $rname[])
}
After that you can try a print_r on $rname and adapt to you.
Try below :-
$a = explode("rname=", index[3]);
echo $a[1;]
Code
$array = array(
'./index.php?module=Rsdfepfdsforts&action=reposfdfdsrtsel&rname=Opdpasfdfypdf',
'./index.php?module=Rexcvpofdsrts&action=reportsel&rname=Pacxvtregcollxcvectionpdf',
);
function getRname($str){
//return null if not found
preg_match('/rname\=([a-zA-Z]+)($|&)/', $str , $matches);
return $matches[1];
}
foreach($array as $str){
echo "Rname: " . getRname($str). "<br/>";
}
Result
Rname: Opdpasfdfypdf
Rname: Pacxvtregcollxcvectionpdf
Try it?

Categories