Regex not working properly in PHP - php

I have this data:
{"names":["George","Eric","Alice"]}
And I want to use preg_match_all to filter out the words in between quotation like this:
$s = $data;
if (preg_match_all('/"([^:]*)"/', $s, $matches)) {
echo join("\n", $matches[1]);
}
But this is outputting names George","Eric","Alice I tried many things but I cant figure it out.

* matches greedy (as much as possible). Use non-greey version: *?
if (preg_match_all('/"([^:]*?)"/', $s, $matches)) {
echo join("\n", $matches[1]);
}
output:
names
George
Eric
Alice
UPDATE
json_decode is more appropriate for this kind of work. Try following:
foreach (json_decode($s, true) as $key => $value) {
echo $key . "\n";
echo join("\n", $value);
}

This is actually JSON string use json_decode to parse it rather than using regex on this:
print_r(json_decode('{"names":["George","Eric","Alice"]}', true));
OUTPUT:
Array
(
[names] => Array
(
[0] => George
[1] => Eric
[2] => Alice
)
)

try this
$strContent = '{"names":["George","Eric","Alice"]}';
$strRegex = '%\"(.+?)\"%s';
if (preg_match_all($strRegex, $strContent, $arrMatches))
{
var_dump($arrMatches[1]);
}

Since your data is json formatted you should really treat is as json and not process it with regex which is to be used for strings. Try this:
$json = '{"names":["George","Eric","Alice"]}';
$data = json_decode($json, true);
foreach($data['names'] as $item) echo "$item\n";
Or without the hard coded "names":
$json = '{"names":["George","Eric","Alice"]}';
$data = json_decode($json, true);
foreach($data as $arr) foreach($arr as $item) echo "$item\n";

Related

How to extract PHP array values and remove data

I have seen a bunch of ways, but none that seem to work. My array data is coming back like this.
Array
(
[0] => RESULT=0
[1] => RESPMSG=Approved
[2] => SECURETOKEN=8cpcwfZhaH02qNlIoFEGZ1wO4
[3] => SECURETOKENID=253cad735251571cebcea28e877f4fd7
I use this:
<?php echo $response[2];?>
too get each out, that works. But I need to remove “SECURETOKEN=” so im left with just the number strings. I have been trying something like this with out success.
function test($response){
$secure_token = $response[1];
$secure_token = substr($secure_token, -25);
return $secure_token;
}
Also Im putting end number into a form input “Value” field. Not that that matters, unless it does?
Thanks
This is what I would do:
$keyResponse = [];
foreach ($response as $item) {
list($k, $v) = explode('=', $item, 2);
$keyResponse[$k] = $v;
}
Now you can easily access just the value part of each item based on the name:
echo $keyResponse['SECURETOKEN']; // output: 8cpcwfZhaH02qNlIoFEGZ1wO4
The advantage to this method is the code still works if the order of the items in $response changes
I get your secure token like this (tested):
<?php
$arr = array(
'RESULT=0',
'RESPMSG=Approved',
'SECURETOKEN=8cpcwfZhaH02qNlIoFEGZ1wO4',
'SECURETOKENID=253cad735251571cebcea28e877f4fd7'
);
$el = $arr[2];
$parts = explode('=', $el);
echo '#1 SECURETOKEN is ' . $parts[1];
// This break just for testing
echo '<br />';
// If you wanted to, you could revise the whole array
$new = array();
foreach( $arr as $el ){
$parts = explode('=', $el);
$new[$parts[0]] = $parts[1];
}
// Which would mean you could then get your securetoken like this:
echo '#2 SECURETOKEN is ' . $new['SECURETOKEN'];

How can I decode a JSON string in PHP?

I am trying to read a string into an array in PHP, but it doesn't work for me.
The string I would like to read:
$output = {"message":"Approved","responseCode":"0","responseCodeDesc":"Transaction Successful"}
The code I am using:
$arr = explode(',', $output);
foreach($arr as $v) {
$valarr = explode(':', $v);
preg_match_all('/"(.*?)"/', $valarr[0], $matches);
$narr[$matches[1][0]][$matches[1][1]] = $valarr[1];
}
Specifically, I would like to access the value for 'message' (i.e., 'Approved').
I tried this, but it still fails:
echo 'MESSAGE ' . $arr['message'];
Here is working code,
$arr = '{"message":"Approved","responseCode":"0","responseCodeDesc":"Transaction Successful"}';
$arr = json_decode($arr, true);
echo $arr['message'];
print_r($arr);
Here is working link
Thats not string, its json..
$array = json_decode($output,true);

Extract parameter from a string

I have to extract a string like this:
index.php?module=Reports&action=abc&rname=Instantpayment
Now my task is to extract report, action and rname value in PHP.
I have tried by using explode(), but I am not able to extract module.
How can I do it?
You could use parse_str() in this case:
$string = 'index.php?module=Reports&action=abc&rname=Instantpayment';
$string = substr($string, strpos($string, '?')+1); // get the string from after the question mark until end of string
parse_str($string, $data); // use this function, stress free
echo '<pre>';
print_r($data);
Should output:
Array
(
[module] => Reports
[action] => abc
[rname] => Instantpayment
)
$yourUrl="module=Reports&action=abc&rname=Instantpayment"
$exploded_array = array();
parse_str($yourUrl, $exploded_array);
$exploded_array['module'];
$exploded_array['action'];
$exploded_array['rname'];
Use $_GET to get query strings from the URL
echo $_GET['module']; //Reports
echo $_GET['action']; // abc
echo $_GET['rname']; // Instantpayment
For getting from the string try explode():
$str ='index.php?module=Reports&action=abc&rname=Instantpayment';
$e = explode('?', $str);
$e1 = explode('&', $e[1]);
foreach($e1 as $v) {
$ex = explode('=', $v);
$newarr[$ex[0]] = $ex[1];
}
print_r($newarr); // Use this array of values you want.
//Array ( [module] => Reports [action] => abc [rname] => Instantpayment )
echo $newarr['module'];
echo $newarr['action'];
echo $newarr['rname'];
You have to access the globale GET variable:
$_GET['module']
$_GET['action']
$_GET['rname']
Try this:
<?php
$temp = "index.php?module=Reports&action=abc&rname=Instantpayment";
$t1 = explode("=",$temp);
for ($i = 1; $i < sizeof($t1); $i++)
{
$temp = explode("&", $t1[$i]);
echo $temp[0] . "\n";
}
?>

JSON and Arrays mixed up (in PHP)

This is what I get from my SQL selection. The data is correct, now I'd like to echo it by foreach.
Array ( [0] => stdClass Object ( [sql_column] => [{"1":"value1", "2":"value2", "3":"value3"}] ) )
What I've tried (and which didn't work) was:
$obj = json_decode($arr);
foreach($obj as $data){
echo $data->sql_column->1; //this should echo "value1", but it doesn't
}
Does anyone see my mistake? Thanks in advance!
If $arr is the array you posted then you can't json_decode it since it's an array and not a JSON string.
//First you need to get the string
$json = $arr[0]->sql_column;
//Then decode
$data = json_decode($json);
//Then loop
foreach($data as $key => $value){
echo "$key = $value \n";
}
Your json seems to be complicated (double dimensional array), but you can fetch values from it in this manner:
foreach($arr as $data){
$json = json_decode($data->sql_column);
$temp = (array)$json[0];
foreach($temp as $k=>$v){
print($v."<br/>");
}
}
I hope you get an idea...
I used foreach for $arr to cover multi values, you can omit that if you want:
$data=$arr[0];
$json = json_decode($data->sql_column);
$temp = (array)$json[0];
foreach($temp as $k=>$v){
print($v."<br/>");
}

converting array containing keys and values into string

I have an array it contains key and value. i would like to converting into a string.
array(
[business_type]=>'cafe'
[business_type_plural] => 'cafes'
[sample_tag]=>'couch'
[business_name]=>'couch cafe'
)
Expected Output:
business_type,cafe|business_type_plural,cafes|sample_tag,couch|business_name,couch cafe
NOTE:
I was searching in StackOverflow and found the below question and it has answer. I want exactly reverse one.
converting string containing keys and values into array
Try
$data = array();
foreach($arr as $key=>$value) {
$data[] = $key.','.$value;
}
echo implode('|',$data);
Another Solution:
function test_alter(&$item1, $key, $delimiter)
{
$item1 = "$key".$delimiter."$item1";
}
array_walk($arr, 'test_alter',',');
echo implode('|',$arr);
Use the foreach() function to go through the array and string the keys/values together...
Assuming your array is called $array
$result = "";
foreach($array as $key => $value){
$result .= $key . "," . $value . "|";
}
It's as simple as that.
EDIT - Thanks Nelson
After that, lost the last |
$result = rtrim($result, "|");
try this
$pieces=array();
foreach(array('key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3') as $k=>$v)
{
$pieces[]=$k.','.$v;
}
echo implode('|', $pieces);

Categories