PHP/MYSQL/JSON:解析复杂的字符串或重新组装为字典



我通过JSON收到一个表示对象的复杂字符串:

<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})

我想将某些东西保存到 MYSQL。 在上面的示例中,我想将字段 offer 和 offernumber 等保存到记录中,如下所示:

$sql = "INSERT into offers (offer,offernumber) VALUES ('test',70)";

当然,要做到这一点,我首先必须解析字符串以获取 offer 的值、offer 编号的值,理想情况下,获取整个对象的键和值。

我应该先将字符串转换为某种数组、字典或数据结构吗? 还是我应该尝试使用正则表达式或其他方法解析字符串? 如果是后者,将不胜感激有关使用什么正则表达式或技术的建议。

提前感谢您的任何建议!

您可以尝试使用 PHP 将字符串转换为对象, 这可能有助于您:

$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);

上面的代码将给定的字符串转换为对象,然后您可以根据需要使用这些属性。

你可以在这里试试这个: PHP 沙盒

最新更新