我正在使用这样的cURL字符串:
<!CDATA[[
var animals = new Array();
animals[0] = new Animal('Skunk', 10, 15, 'pic1.png');
animals[1] = new Animal('Dog', 17, 11, 'pic2.png');
animals[2] = new Animal('Gorilla', 144, 95, 'pic3.png');
]]>
等等。我添加了新行只是为了更好地说明该字符串的结构。问题是如何使用PHP访问:
简单地说我想要使用PHP这样的东西:
array{
[0] => array([0] => 'Skunk', [1] => 10, [2] => 15, [3] => 'pic1.png')
}
我希望有一些其他解决方案可以爆炸,preg_match等...
感谢您的建议。
答案 0 :(得分:1)
<强>答案强>
没有本土方式。如果您控制了被调用的页面,我建议将数据输出为json并使用php的方法json_decode($json, true)
。
如果您无法控制它,您有两种可能性:
因此,以下内容将帮助您进行解析。
<强> Therory 强>
删除()
基本上,您将使用此正则表达式提取所有beetween (
和)
/(([^)] +))/
您将按,
<强>实践强>
没有测试过这个或者检查过这个是否存在snytax错误,因为我这里没有IDE:
//Remove Initializer Brackets
$dataString = str_replace('()', '', $dataString);
//Your final Animal Collection
$animalCollection = [];
//Find each Animal Definition, which is beetween ( and )
preg_match_all('/\(([^)]+)\)/', $dataString, $matches);
foreach ($matches[0] as $match) {
//Explode partes of the animal
$expCollection = explode(',', $match);
//Create a animal array
$animal = [];
foreach ($expCollection as $expPart) {
//Copy the cleaned animal parts to our array
$animal[] = trim(str_replace('\'', '', $expPart));
}
//fill animal Collection
$animalCollection[] = $animal;
}
//Show content
print_r($animalCollection)
答案 1 :(得分:1)
我会用正则表达式来做这件事。给出你的样本字符串:
$curl = "<!CDATA[[
var animals = new Array();
animals[0] = new Animal('Skunk', 10, 15, 'pic1.png');
animals[1] = new Animal('Dog', 17, 11, 'pic2.png');
animals[2] = new Animal('Gorilla', 144, 95, 'pic3.png');
]]>";
preg_match_all("/\((.+)\)/", $curl, $match); //this matches each Animal
$result = array();
foreach ($match[1] as $key => $elem){
$result[] = explode(',', $elem);
}
print_r($result);
输出:
Array
(
[0] => Array
(
[0] => 'Skunk'
[1] => 10
[2] => 15
[3] => 'pic1.png'
)
[1] => Array
(
[0] => 'Dog'
[1] => 17
[2] => 11
[3] => 'pic2.png'
)
[2] => Array
(
[0] => 'Gorilla'
[1] => 144
[2] => 95
[3] => 'pic3.png'
)
)