This question already has an answer here:
Remove comments from JSON data
(1 answer)
Closed 4 years ago.
In a task I had to write comments in JSON files and decode them using PHP. I share it. Maybe it helps someone else. The regex was tough.
Remove the comments with regular expression
$jsonStringWithComments = file_get_contents ( "jsonFileWithComments.json" );
$pattern = '/(((?<!http:|https:)\/\/.*|(\/\*)([\S\s]*?)(\*\/)))/im';
$decodedObject = json_decode ( preg_replace ( $pattern, '', $jsonStringWithComments ) );
This regular expression can capture "one-line" comments, start double slashes // or "multi-line" comments between slash asterisk /* and asterisk slash */.
With it, you can parse JSON like the following:
{
"lorem": "ipsum",
"dolor":/* inline comment */ "sit amet",
"consectetur": "adipiscing",
/*
multi
line
comment
*/
"Pellentesque": "ultrices",
//single line comment
"lectus": "nec",
"elit": "dictum",
"url": "http://example.com"
}
Related
This question already has answers here:
What special characters must be escaped in regular expressions?
(13 answers)
Closed 2 years ago.
Here the data i want to get
<script>
window['ads_imgs'] = '{"1734275":"https:\/\/media2.lajumate.ro\/media\/i\/cart\/5\/173\/1734275_chevrolet-aveo-5-usi_7.jpg","11570560":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/0\/115\/11570560_audi-a5-sportback-2012-163cp-impecabila-tinuta-in-garaj_14.jpg","3741462":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/2\/374\/3741462_seat-leon-fr-extra-full-dpf_1.jpg","11596338":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/8\/115\/11596338_toyota-auris-12-115-cp-2016_1.jpg","11687842":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/2\/116\/11687842_opel-astra-h-model-2008_1.jpg","11034666":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/6\/110\/11034666_hyundai-tucson-2008_10.jpg","11596195":"https:\/\/media2.lajumate.ro\/media\/i\/cart\/5\/115\/11596195_volkswagen-passat-20-150-cp-2017_1.jpg","10637740":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/0\/106\/10637740_renault-megane-iii-15-dci-90cp-2017_21.jpg","11884407":"https:\/\/media2.lajumate.ro\/media\/i\/cart\/7\/118\/11884407_audi-a4-b7_1.jpg","11889991":"https:\/\/media2.lajumate.ro\/media\/i\/cart\/1\/118\/11889991_vw-touran-19-tdi-105-cp-7-locuri-impecabil-highline_1.jpg","10637645":"https:\/\/media2.lajumate.ro\/media\/i\/cart\/5\/106\/10637645_renault-kadjar-16-dci-130cp-2017_27.jpg","10859634":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/4\/108\/10859634_bmw-z4-35i-cabrio-2009_16.jpg","11889990":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/0\/118\/11889990_vw-passat-20-tdi-170-cp-dsg-automat-highline-full_1.jpg","10803942":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/2\/108\/10803942_mercedes-vito-44_1.jpg","10803920":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/0\/108\/10803920_mercedes-vito-44_11.jpg","11818572":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/2\/118\/11818572_opel-zafira-20l-diesel-7-locuri_4.jpg","11767296":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/6\/117\/11767296_ford-mondeo_4.jpg","9534043":"https:\/\/media2.lajumate.ro\/media\/i\/cart\/3\/953\/9534043_suzuki-sx4_5.jpg","11825640":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/0\/118\/11825640_bmw-520d-f10-automat-m-pachet_1.jpg","11825285":"https:\/\/media2.lajumate.ro\/media\/i\/cart\/5\/118\/11825285_mitshubishi-pajero-pinin-18-gdi_1.jpg","11319696":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/6\/113\/11319696_vw-caddy-4x4-euro5_1.jpg","11358821":"https:\/\/media2.lajumate.ro\/media\/i\/cart\/1\/113\/11358821_bmw-seria-1-e87_1.jpg","11889964":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/4\/118\/11889964_audi-a5-full-led-170cp-schimb-cu-platforma-auto_1.jpg","11675889":"https:\/\/media2.lajumate.ro\/media\/i\/cart\/9\/116\/11675889_audi-a3-s-line-quattro_1.jpg","8642541":"https:\/\/media2.lajumate.ro\/media\/i\/cart\/1\/864\/8642541_toyota-rav-4_1.jpg","11309651":"https:\/\/media2.lajumate.ro\/media\/i\/cart\/1\/113\/11309651_ford-focus_1.jpg","11309545":"https:\/\/media2.lajumate.ro\/media\/i\/cart\/5\/113\/11309545_bmw-318d_1.jpg","11309534":"https:\/\/media1.lajumate.ro\/media\/i\/cart\/4\/113\/11309534_ford-s-max_1.jpg"}';
</script>
How i can get the id and images link using html dom.
Here the code i am getting the exact script but i cant get the value of window['ads_imgs']
//receiving the data from script tag
$data = $responseData->find('script',11);
preg_match("/window['ads_imgs'] = '(.*)'/", $data, $m);
print_r($m);
exit();
}
There's a small error in your regex. You need to escape the square brackets as follows. You also need to use curly brackets for the enclosure because that's the actual sentinel shown in your "data":
preg_match("/window\['ads_imgs'\] = '{.*}'/", $data, $m);
You likely just want the json itself though. For this you can do another regex match on $m[0] as follows:
preg_match("/{.*}/", $m[0], $j_str);
Here's a complete test with sample data:
$data = " window['ads_imgs'] = '{\"1734275\":\"https:\/\/media2.lajumate.ro\/media\/i\/cart\/5\/173\/1734275_chevrolet-aveo-5-usi_7.jpg\",\"a\":{\"b\":\"bb\"}}' ";
preg_match("/window\['ads_imgs'\] = '{.*}'/", $data, $m);
preg_match("/{.*}/", $m[0], $j_str);
$json = json_decode($j_str[0], true);
print_r($json);
Outputs:
Array
(
[1734275] => https://media2.lajumate.ro/media/i/cart/5/173/1734275_chevrolet-aveo-5-usi_7.jpg
[a] => Array
(
[b] => bb
)
)
This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 4 years ago.
I get the content from an URL: http://money18.on.cc/js/real/hk/quote/16981_r.js
The content of this file is something like this:
M18.r_16981 = {
"ltt": '2018/06/21 11:43',
"np": '0.050',
"iep": '0.000',
"iev": '0',
"ltp": '0.050',
"vol": '940000',
"tvr": '49860',
"dyh": '0.060',
"dyl": '0.049'
};
I want to extract the number after "vol", i.e. 940000.
And this is my php:
<?php
$content = file_get_contents("http://money18.on.cc/js/real/hk/quote/16981_r.js");
echo $content."<br>";
preg_match("/(?<=vol\": ').*(?=', \"tvr)/", $content, $output_array);
print_r(array_values($output_array));
?>
The result returns nothing. Is the Regex wrong or any other problem?
Thanks.
In your positive lookahead (?= you could replace the whitespace with \s* to match zero or more (or \s+ to match one or more) whitespace characters.
(?<=vol": ').*(?=',\s*"tvr)
Regex demo
Php demo
Bit of a long shot but...
If that content is actually meant to represent JSON and you have control over it:
get it into proper format as it is much easier and secure to get the data you want out of it then.
$jsonString = <<<JSON
{
"ltt": "2018/06/21 11:43",
"np": "0.050",
"iep": "0.000",
"iev": "0",
"ltp": "0.050",
"vol": "940000",
"tvr": "49860",
"dyh": "0.060",
"dyl": "0.049"
}
JSON;
$jsonAsArray = json_decode($jsonString, true);
var_dump($jsonAsArray['vol']);
This question already has answers here:
Extract HTML attributes in PHP with regex [duplicate]
(2 answers)
Closed 7 years ago.
i have the following html structure :
<div data-provincia="mi" data-nazione="it" ecc...
I'm trying to take "mi" with preg_match function.
This is my code :
$pattern = '/data-provincia=*"[a-zA-Z]*"/';
preg_match($pattern,$element,$provincia);
I think that the code is right but it doesn't match with anything.
Where i'm wrong?
Thanks.
You might want to use the quantifier + (1 or more) next to the character class between brackets, and remove the first star. Also added a subtpattern for you to get exactly the part you want. Give it a try :
$pattern = '/data-provincia="([a-zA-Z]+)"/';
preg_match($pattern,$element,$provincia);
echo $provincia[1];
$element = '<div data-provincia="mi" data-nazione="it" ecc...>';
$pattern = '/<div[^>]*data-provincia=\"([^\"]+)\"[^>]*>/';
preg_match($pattern,$element,$provincia);
print_r($provincia[1]);
In addition to my comment, for this simple attribute you can use the following regex:
$regex = '/data-provincia="([^"]*)/i';
preg_match($regex,$element,$matches);
echo $matches[1];
Basically match everything except a double quote as many times as possible (or none). But please at least consider using a Parser for this task, regular expressions were not meant to deal with it.
Its working fine for me
$element = '<div data-provincia="mi" data-nazione="it"></div>';
$pattern = '/data-provincia=*"[a-zA-Z]*"/';
$matches= array();
preg_match($pattern,$element, $matches);
if (!empty($matches)) {
foreach ($matches as $eachOne) {
//code to remove unwanted
$text = trim(preg_replace('/^data-provincia\=/', '', $eachOne), '""');
echo " $eachOne; $text";
}
}
This question already has answers here:
PHP ltrim behavior with character list
(2 answers)
Closed 8 years ago.
I have this code..
$homepage1 = 'datastring=/mac_project/portfolio/kitchen/images/03.jpg';
$trimmed = ltrim($homepage1, 'datastring=/mac_project');
echo $trimmed;
I get the output as folio/kitchen/images/03.jpg. It's missing the /port from the /portfolio directory.
Full output should've been /portfolio/kitchen/images/03.jpg
Why not do the simple str_replace() ?
$homepage1 = 'datastring=/mac_project/portfolio/kitchen/images/03.jpg';
$trimmed = str_replace('datastring=/mac_project','',$homepage1);
echo $trimmed;// "prints" /portfolio/kitchen/images/03.jpg
The second parameter for ltrim is for character_mask, which means all the chars in the list will be trimmed.
You could use str_replace(), or if you want to replace only at the beginning of the string by preg_replace():
$trimmed = preg_replace('~^datastring=/mac_project~', '', $homepage1);
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
PHP preg_match_all: Extract comma seperated list
I have a string that looks like: [something ="1,2,3"]
I need get everything between the quotes into a string. I'm sure that preg_match is the way to do this but i'm not sure of the expression to use.
$content = [something = "1,2,3"];
$new_string = preg_match('?regex?','$content');
Try this:
$content = '[something = "1,2,3"]';
if (preg_match('/"([^"]+)"/', $content, $matches)) {
$matchedContent = $matches[1];
}