PHP: Extract specific word after specific word in a string? - php

I have a string that looks like this:
{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}
i only need the value for the country_name from that string.
so I tried this:
$country = '{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}';
if (preg_match('#^country_name: ([^\s]+)#m', $country, $match)) {
$result = $match[1];
}
echo $result;
but there is nothing being echoed in the $result
Could someone please advise on this issue?

$country = json_decode('{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}');
echo $country->country_name;
What you have there is a JSON string.
JSON stands for JavaScript Object Notation.
PHP can decode it into an Array or Object via json_decode($string, FALSE);
The 2nd parameter by default is FALSE, which means it will convert the string into an object, which you can then access as I showed you above.

If for some reason you don't want to use JSON you can give the following a try. Note that using JSON is the recommended way doing this task.
$country = '{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}';
$temp = explode('"country_name":', $country); //Explode initial string
$temp_country = explode(',', $temp[1]); //Get only country name
$country_name = str_replace('"', ' ', $temp_country[0]); //Remove double quotes
echo $country_name;
Result:
Ireland

Try this:
<?php
$country=json_decode('{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}')
$result=$country->country_name;
echo $result;
?>

This looks like a json string. Read more about JSON.
Use it like this:
$foo = '{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}';
$bar = json_decode($foo, true);
echo $bar['country_name'];
This can be used with any key from that string (eg ip, city)
More about json_decode.

Related

PHP : Convert php dictionary data set to key:valu pair

I have data set smiller to dictonary and I want to get key value pair for this data.
here is DATA SET:
$data = "{u'test_field2': u'NONE', u'test_field3': u'NONE', u'test_account': u'NONE', u'test_account_1': u'NONE'}"
I am doing json_decode($data, true); but have no luck with it
Sorry If I am unclear.f
BTW I am doing it in PHP
the result should be like this:
test_field2: NONE
test_field3: NONE
Since your data is invalid json because of that u in it here is a solution
json_decode(str_replace("'",'"',str_replace("u'","'",$data)), true);
Should do the trick
You've to try like this because on your existing code couple of issue exists.
Replace Unnecessary character u' with '
Replace single quotes(') on json string. For json double quotes(") is permitted.
So just search these two characters and replace with '' and " respectively.
<?php
$data = "{u'test_field2': u'NONE', u'test_field3': u'NONE', u'test_account': u'NONE', u'test_account_1': u'NONE'}";
$search = ["u'","'"];
$replace = ["'",'"'];
$without_u = str_replace($search,$replace,$data);
$array = json_decode($without_u, true);
print '<pre>';
print_r($array);
print '</pre>';
?>
DEMO: https://eval.in/1032316

Extracting data from Json in Php

I have this Json Object Below, I want to extract this data and output it in PHP
{"seat_booked":"A5","0":"A5","1":"A3"}
then get them into this format
$seat_booked = "'A5', 'A5', 'A3'";
How can I do this?
I hope you are looking for this, its very simple example by using json_decode():
$string = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = json_decode($string,true);
$resuiredString = '"'."'".implode("','", $decoded)."'".'"';
echo $resuiredString;
Result:
"'A5','A5','A3'"
Side Note:
I suggest you to learn about variable concatenation.
PHP Concatenation
Another solution:
$json = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = array_map(
function($val) {
return "'". $val."'";
},
array_values(json_decode($json, true))
);
To get an object from a json in php you can use json_decode has explained here.
But you have another problem, your json is wrong!
If you want to represent a single dimensional array you should at least do this
["A5","A5","A3"]
Finally, using json_decode:
$obj = json_decode('["A5","A5","A3"]');
var_dump($obj);
Also, you could do something like:
{"0":"A5","1":"A5","2":"A3"}
$obj = json_decode('{"0":"A5","1":"A3", "2": "A5"}', true);
var_dump($obj);
Edit:
It's not very clear from your question if you are trying to get back an object from a json or if you just want to get a string from it.
If what you need is an string then you don't even need json, you could do this by string manipulation and/or using regex.
But just for completeness, if a quoted comma separated string is what you need you can do this:
$array = json_decode('["A5","A5","A3"]');
$str = implode("','",$array);
$str = "'" . $str . "'";
var_dump($str);

Extract JSON Array from data

I am requesting data from another website and expecting a clean json array in return.
However I am getting this instead:
<pre></pre>{"Status":"Success","Result":1}
which won't parse with json_decode();.
How do I extract the JSON array out of this data so I can parse it?
Note: I am not in control of the code I am requesting the data from.
try this
$output_array = array();
$badstr = '<pre></pre>{"Status":"Success","Result":1}';
preg_match("/{.*}/", $badstr, $output_array);
in $output_array[0] you have your json string.
Assuming that <pre></pre> is constant, then just a simple substring operation:
$badstr = '<pre></pre>{"Status":"Success","Result":1}';
$goodstr = substr($badstr, 11);
But you really should yell at the server admins for sending out bad json in the first place. There's no excuse for this kind of thing. It's probably some debug code they forgot to take out.
If you want it to work both now, and once the issue will be fixed, you can do this:
$result = '<pre></pre>{"Status":"Success","Result":1}';
if (strpos($result ,'<pre>') !== false)
{
$array = json_decode(substr($result , 11));
}
else
{
$array = json_decode($result);
}
Only remove <pre></pre>, only if it's the first thing:
$response = preg_replace('#^<pre></pre>#', '', $response);
How about simply string replace?
Like so:
$json_string = '<pre></pre>{"Status":"Success","Result":1}';
$json = str_replace("<pre></pre>", "", $json_string);
echo $json;
Output:
{"Status":"Success","Result":1}
If you don't expect any html tags in your output, you can also use strip_tags():
$not_json = '<pre></pre>{"Status":"Success","Result":1}';
$json_string = strip_tags($json);
$result = json_decode($json_string);

Regex to convert enum field value to json

Is there a way to quickly convert simple enum data format like this
enum('one','two','three')
to json?
I wrote a code:
$res = $rst->fetch_assoc();
$type = $res['DATA_TYPE'];
$json = preg_replace('/\'/','"', $res['COLUMN_TYPE']);
$json = preg_replace("/^$type\(/",'[', $json);
$json = preg_replace('/\)/',']', $json);
return json_decode($json);
But here 3 substitutes for each part of original string: single quotes, 'enum( ' and ')'. I have read a lot about regex for converting enum but could not figure out how to do it in one leap.
replace your code with this, it should have the desired result
$res = $rst->fetch_assoc();
$type = $res['DATA_TYPE'];
preg_match_all('/\'([^\']*)\'/',$res['COLUMN_TYPE'],$matches);
return $matches[1];
you said you wanted json, but you are actually using json_decode() at the end to return an array, preg_match_all already gives you an array, so no need for decoding, if you actually want json, you could just use json_encode($matches[1])
This should work out for you.
<?php
$str = "enum('one','two','three')";
$start = strpos($str, "(")+1;
$str = substr($str, $start, strrpos($str,")") - $start);
$parts = explode(",", $str);
$enum = array_map(function($a){
return trim($a, "'");
},$parts);
return json_encode($enum);

getting value using explode

I am trying to parse following string...
IN.Tags.Share({"count":180,"url":"http://domain.org"}
is my following approach correct to get the value of count?
$str = 'IN.Tags.Share({"count":180,"url":"http://domain.org"}';
$data = explode(':', $str);
$val = explode(',', $data[1]);
return $val[0];
Or is there any better way to handling this type of strings? I think it could be done using regex as well.
thanks.
If course I'm not sure if your format will be constant, but part of your string looks like JSON. If always like this, you could do:
$str = str_replace('IN.Tags.Share(', '', $str);
$values = json_decode($str);
echo $values->count;
I would suggest pulling out the JSON by applying this regex to the string: IN\.Tags\.Share\((.*)\. Pull out the first group, and use json_decode: http://php.net/manual/en/function.json-decode.php
That way, you can directly access the data. It will support complex data structures as well.

Categories