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);
Related
I receive a complicate string through JSON that represents an object:
<Offers: 0x170483070> (entity: Offers; id: 0xd00000000b880006 <x-
coredata://03C4A684-2218-489C-9EF6-42634ED10552/Offers/p738> ; data: {\\n
topic = nil;\\n topid = 9403;\\n hasserverid = nil;\\n isprivate = nil;\\n
lasttouched = \\\"2018-07-08 16:49:01 +0000\\\";\\n lastviewed = nil;\\n
localid = 42;\\n needpicsync = nil;\\n needsync = nil;\\n secondorder
= 0;\\n oid = 0;\\n offer = test;\\n offerdone = nil;\\n offernumber =
70;\\n userid = 1;\\n wasdeleted = nil;\\n whenadded = \\\"2018-07-08
16:04:20 +0000\\\”;\\n})
I would like to save certain things to MYSQL. In the above example, I would like to save the fields offer and offernumber among others to a record with something like:
$sql = "INSERT into offers (offer,offernumber) VALUES ('test',70)";
To do this, of course, I first have to parse the string to get the value for offer, the one for offer number and ideally, the keys and values for the entire object.
Should I first convert the string into some sort of array,dictionary or data structure? Or should I try to parse the string using regex or some other method? If the latter, would appreciate suggestions on what what regex or technique to use.
Thanks in advance for any suggestions!
You can try to convert the string into a object with PHP,
this may help you:
$input = "**The input string**";
// Remove the escaped new lines
$jsonString = str_replace("\\n", "\n", substr($input, strpos($input, "data: ")+5));
$jsonString = substr($jsonString, 0, strlen($jsonString) - 1);
// Convert the equals, semicolons and remove the escaped backslash
$jsonString = str_replace(";", ",", $jsonString);
$jsonString = str_replace("=", ":", $jsonString);
$jsonString = str_replace('\\', '', $jsonString);
$matches = array();
// Use regex to get json key-value
if(preg_match_all('/(\w+)\s*\:\s*(.+)\s*\,/m', $jsonString, $matches,PREG_SET_ORDER, 0)){
// Iterate the matches and enclose key and value into double quotes
foreach($matches as $item){
// Enclose the value if isn't a number or a date
if(strpos(trim($item[2]), '"') !== 0 && !is_numeric($item[2])){
$item[2] = '"'.$item[2].'"';
}
// Replace in json string
$jsonString = str_replace($item[0], '"'.$item[1].'"'.' : '.$item[2].',', $jsonString);
}
}
// Remove last comma
$jsonString = substr($jsonString, 0, strlen($jsonString) - 3) . '}';
// Transform json string to object
$jsonObject = json_decode($jsonString);
// Show the json string
echo($jsonString);
// Display the object
var_dump($jsonObject);
the above code convert the given string to an object and then you can use the properties as you need.
you can try this here: PHP Sandbox
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);
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.
How can I use str_replace method for replacing a specified portion(between two substrings).
For example,
string1="www.example.com?test=abc&var=55";
string2="www.example.com?test=xyz&var=55";
I want to replace the string between '?------&' in the url with ?res=pqrs&. Are there any other methods available?
You could use preg_replace to do that, but is that really what you are trying to do here?
$str = preg_replace('/\?.*?&/', '?', $input);
If the question is really "I want to remove the test parameter from the query string" then a more robust alternative would be to use some string manipulation, parse_url or parse_str and http_build_query instead:
list($path, $query) = explode('?', $input, 2);
parse_str($query, $parameters);
unset($parameters['test']);
$str = $path.'?'.http_build_query($parameters);
Since you're working with URL's, you can decompose the URL first, remove what you need and put it back together like so:
$string1="www.example.com?test=abc&var=55";
// fetch the part after ?
$qs = parse_url($string1, PHP_URL_QUERY);
// turn it into an associative array
parse_str($qs, $a);
unset($a['test']); // remove test=abc
$a['res'] = 'pqrs'; // add res=pqrs
// put it back together
echo substr($string1, 0, -strlen($qs)) . http_build_query($a);
There's probably a few gotchas here and there; you may want to cater for edge cases, etc. but this works on the given inputs.
Dirty version:
$start = strpos($string1, '?');
$end = strpos($string1, '&');
echo substr($string1, 0, $start+1) . '--replace--' . substr($string1, $end);
Better:
preg_replace('/\?[^&]+&/', '?--replace--&', $string1);
Depending on whether you want to keep the ? and &, the regex can be mofidied, but it would be quicker to repeat them in the replaced string.
Think of regex
<?php
$string = 'www.example.com?test=abc&var=55';
$pattern = '/(.*)\?.*&(.*)/i';
$replacement = '$1$2';
$replaced = preg_replace($pattern, $replacement, $string);
?>
I have a string that looks a little like this, world:region:bash
It divides folder names, so i can create a path for FTP functions.
However, i need at some points to be able to remove the last part of the string, so, for example
I have this world:region:bash
I need to get this world:region
The script wont be able to know what the folder names are, so some how it needs to be able to remove the string after the last colon.
$res=substr($input,0,strrpos($input,':'));
I should probably highlight that strrpos not strpos finds last occurrence of a substring in given string
$tokens = explode(':', $string); // split string on :
array_pop($tokens); // get rid of last element
$newString = implode(':', $tokens); // wrap back
You may want to try something like this:
<?php
$variable = "world:region:bash";
$colpos = strrpos($variable, ":");
$result = substr($variable, 0, $colpos);
echo $result;
?>
Or... if you create a function using this information, you get this:
<?php
function StrRemoveLastPart($string, $delimiter)
{
$lastdelpos = strrpos($string, $delimiter);
$result = substr($string, 0, $lastdelpos);
return $result;
}
$variable = "world:region:bash";
$result = StrRemoveLastPart($variable, ":");
?>
Explode the string, and remove the last element.
If you need the string again, use implode.
$items = array_pop(explode(':', $the_path));
$shotpath = implode(':', $items);
Use regular expression /:[^:]+$/, preg_replace
$s = "world:region:bash";
$p = "/:[^:]+$/";
$r = '';
echo preg_replace($p, $r, $s);
demo
Notice how $ which means string termination, is made use of.
<?php
$string = 'world:region:bash';
$string = implode(':', explode(':', $string, -1));