regex wrap strings in quotes - php

I have an array like the example below but much much bigger (4000 lines long):
array(
"id" => array(
"a" => "",
"b" => "",
"c" => Needs Quotes Around Me
), "id" => array(
"a" => "",
"b" => "",
"c" => Needs Quotes Around Me
"d" => Needs Quotes Around Me
)
);
The string values for some reason dont have the quotes ("") around them and the colon seperator. Some of the strings are numbers but can be treated as a string and some have spaces and the # symbols as some are email addresses but I need to wrap all of them in "STRING HERE",
Im trying to use reg_replace with something like this =>\s([a-zA-Z0-9\#\s])+$ but it doesnt replace the matched string with the string it found? Ive done quite a bit of googling but cant seem to get it right, please tell me where Im going wrong.
What I end up with is:
array(
"id" => array(
"a" => "",
"b" => "",
"c" => "[a-zA-Z0-9\#\s]",
), "id" => array(
"a" => "",
"b" => "",
"c" => "[a-zA-Z0-9\#\s]",
"d" => "[a-zA-Z0-9\#\s]",
)
);

This perl script works for the example given
perl -pe 's/(?<==> )(?!"|array\()(.*)/"$1",/' EXAMPLEFILE.txt
the following output is produced:
array(
"id" => array(
"a" => "",
"b" => "",
"c" => "Needs Quotes Around Me",
), "id" => array(
"a" => "",
"b" => "",
"c" => "Needs Quotes Around Me",
"d" => "Needs Quotes Around Me",
)
);

It required placing circular brackets around the regex. As simple as this sounds its only easy when you know how.

Related

php regex split string with phone numbers to a few elements in the array

How split string with phone numbers to a few elements in the array?
For example, we have string like this:
"phone" => "+7 (343) 228-02-08 +7 (343) 203-209-3" or "phone" => "8 (800) 555-92-86 8 (499) 322-16-40 8 (812) 426-10-38"
But we need to make it:
"phone" => [
"0" => "+7 (343) 228-02-08",
"1" => "+7 (343) 203-209-3",
]
and for another
"phone" => [
"0" => "8 (800) 555-92-86 8",
"1" => "8 (499) 322-16-40",
"2" => "8 (812) 426-10-38",
]
I tried to find some ready-made solutions, but nothing could be found. Regular expressions - is too complicated for me ...
Instead of split you can use matching using preg_match_all function using this regex:
/\+?\d\h*\(\d{3}\)\h*[\d-]+/
RegEx Demo

Change all strings into their real types in array

I have an array like this :
[▼
0 => array:47 [▼
"ProductID" => "37883"
"ProductCode" => "G-49211"
"ProductName" => "Preludes"
"StockStatus" => "2"
"LastModified" => "2014-02-27T09:50:00-08:00"
"LastModBy" => "1"
"ProductPopularity" => "110"
"AutoDropShip" => "N"
1 => [
"ProductID" => "37884"
"ProductCode" => "G-49212"
"ProductName" => "Preludes "
"StockStatus" => "2"
"LastModified" => "2014-02-27T09:50:00-08:00"
"LastModBy" => "1"
"ProductPopularity" => "110"
"AutoDropShip" => "N"
]
]
but all values of this array are strings. I want to iterate over this array and cast its values to their original types. if ProductID is integer I want to convert it to integer. Convert dates to real date blabla.
Can this be done ?
There isnt any real function in php that can parse away array elements based on their data types, but still you can do it using preg_match pattern matching techniques, by recognizing the characters in each element and then type converting them
idea :- use a foreach loop and take each element and apply preg_match to check what kind of data that is and then set a data type for it :)

Using preg_replace to add quotes to array

I have this array:
$array = '[[Smarties, 50g, 3, 1.99],
[M&Ms Peanut, 49g, 3, 1.99],
[Oreo Cookies, 300g, 1, 3.99],
[Pepsi, 355ml, 3, 1.29]]';
I need to use json_decode, so I need to find a way to surround the information inside in quotes like this:
[["Smarties", "50g", "3", "1.99"],
["M&Ms Peanut", "49g", "3", "1"."99"],
["Oreo Cookies", "300g", "1", "3.99"],
["Pepsi", "355ml", "3", "1.29"]]
I tried using preg_replace, and this is what I'm currently getting (close, but it's separating the prices into two and also separating two-word names into two.):
[["Smarties", "50g", "3", "1"."99"],
["M"&"Ms" "Peanut", "49g", "3", "1"."99"],
["Oreo" "Cookies", "300g", "1", "3"."99"],
["Pepsi", "355ml", "3", "1"."29"]]
I'm having a really hard time understanding preg_replace and I'm hoping someone might be able to help.
Is there a way to use the separating commas as guides to determine where to put the quotes?
For a somewhat crude, but context-aware regex one could use:
$str = preg_replace("~ [\[\],\s]*\K [^,\[\]]+ ~x", '"$0"', $str);
↑ ↑
skip ][, capture non-
+ space commas/brackets
Where the charclass before \K skips structural characters, and the second […] only finds anything but commas and brackets - which then is wrapped in quotes.
One not optimal, but working example:
$result = json_decode(strtr(strtr($yourString, array('['=>'["', ']'=>'"]', ', '=>'","', ']","['=>'],[')), array(']","[' => '],[', '["[' => '[[', ']"]' => ']]')), true);
Process this string, something like,
$sample = explode('],', $array);
foreach ($sample as &$v)
{
$v = array_map('trim', explode(',', trim($v, '[ ]')));
}
Now, array becomes,
array (
0 =>
array (
0 => 'Smarties',
1 => '50g',
2 => '3',
3 => '1.99',
),
1 =>
array (
0 => 'M&Ms Peanut',
1 => '49g',
2 => '3',
3 => '1.99',
),
2 =>
array (
0 => 'Oreo Cookies',
1 => '300g',
2 => '1',
3 => '3.99',
),
3 =>
array (
0 => 'Pepsi',
1 => '355ml',
2 => '3',
3 => '1.29',
),
)
Simply, json_encode() will give,
string '[["Smarties","50g","3","1.99"],["M&Ms Peanut","49g","3","1.99"],["Oreo Cookies","300g","1","3.99"],["Pepsi","355ml","3","1.29"]]' (length=128)

PHP JSON_encode output

This is my first time using PHP and I am making a script that will output text in JSON format. However I am encountering problems with the formatting.
Can someone explain why my browser renders the following code as..
"1", 'b' => "2", ), array( 'a' => "1", 'b' => "2", 'c' => "3", ) ) ); ?>
instead of something like this?
[
[ { "a" : "1" }, { "b" : "2" } ],
[ { "a" : "1" }, { "b" : "2" }, { "c" : "3" } ]
]
Code:
<body>
<?php
echo json_encode(
array(
array(
'a' => "1",
'b' => "2"
),
array(
'a' => "1",
'b' => "2",
'c' => "3"
)
)
);
?>
</body>
Your code is correct, but the setup doesn't seem right. Your PHP code isn't evaluated. What happens if you put nothing but
<?php phpinfo(); ?>
into your file? Does it show only the code or a long table with all kinds of infos? If it's the former, then you need to find out how to get your webserver to interpret the embedded PHP code before sending it to your browser.
Save file as YourFile.php
Run on Xampp server like localhost/yourFile.php , not like D://File....bla bla
You saved your file as html.
Change your file from FileName.html to FileName.php

json multi array syntax

I create array for json this's multiple array condition with syntax :
$row_set = array(
"err" => "",
"msg" => "",
"data" => array(
"f" => "",
"hotel"=> array(
"att" => "",
"name" => "name",
"city" => "",
"country" => ""
),
"city" => array(
"att" => "",
"name" => "",
"region" => "",
"country" => "",
"nr_hotels" => ""
)
)
);
echo json_encode($row_set);
But when I test it in jsonlint.com there is an error :
Parse error on line 1:
array("err"=>"","ms
^
Expecting '{', '['
Please help me. Where is the error from my syntax?
Your code generates:
{"err":"","msg":"","data":{"f":"","hotel":{"att":"","name":"name","city":"\r\n","country":""},"city":{"att":"","name":"","region":"","country":"","nr_hotels":""}}}
which is perfectly valid JSON.
You are parsing PHP code, not JSON in validator.
Your code is run perfect on jsonlint
$row_set =array(
"err"=>"",
"msg"=>"",
"data"=>array(
"f"=>"",
"hotel"=>array(
"att"=>"",
"name"=>"name",
"city"=>"",
"country"=>""
),
"city"=>array(
"att"=>"",
"name"=>"",
"region"=>"",
"country"=>"",
"nr_hotels"=>""
)
));
echo json_encode($row_set);
Output
{"err":"","msg":"","data":{"f":"","hotel":{"att":"","name":"name","city":"","country":""},"city":{"att":"","name":"","region":"","country":"","nr_hotels":""}}}
You have to copy json_encode output on jsonlint and you tried to copy php array which is wrong.
Check Output

Categories