var coords = {'x' : 982, 'y' : 1002 };

当通过curl访问时,api返回上述代码。
我需要将x和y值解析为变量。这两个值的长度也不总是相同的。我不知道最好的办法是什么。
我的想法是使用substr截断前面和后面,所以它是'x' : 982, 'y' : 1002,使用explode得到''ccc>另一个与x' : 982的var,然后再次使用'y' : 1002获得explode982,最后删除空格。
我不确定这条路是否正确。这是正确的方法还是你会用另一种方法?
另外,我使用的api是针对javascript的,但我使用的是php,它们没有php
应用程序编程接口。
编辑:
我有:
<?php
$result = "var coords = {'x' : 982, 'y' : 1002 };";
$result = substr($result, 13);
$result = substr($result, 0,strlen ($result) - 1);
$json_obj = json_decode($result);
$x_coord = $json_obj->{'x'};
$Y_coord = $json_obj->{'y'};
echo 'x:' . $x_coord;
echo '<br>';
echo 'y:' . $y_coord;
?>

但这似乎行不通。

最佳答案

json_decode无法工作,因为尽管字符串是有效的javascript,但它不是有效的json。
如果字符串格式与您发布的完全一样,我只需使用preg_match_all

preg_match_all('/([0-9]+)/', $input, $matches);
list($x, $y) = $matches[0];

原因很简单:虽然不需要正则表达式就可以完成,但代码越少,问题就越少。

10-07 19:38