我正试图找到这个名字&来自PHP内的API的 JSON 响应中的贴纸图片,我设法让preg_match_all
找到 src 属性,但我是努力使它适用于图像的相应名称,这是我的 JSON 响应字符串
$string = '"<br><div id=\"sticker_info\" name=\"sticker_info\" title=\"Sticker Details\" style=\"border: 2px solid rgb(102, 102, 102); border-radius: 6px; width=100; margin:4px; padding:8px;\"><center><img width=64 height=48 src=\"https:\/\/steamcdn-a.akamaihd.net\/apps\/730\/icons\/econ\/stickers\/cologne2016\/sig_pasha.9f41c874350c06e9a902bea06a5228ceccb25ee1.png\"><img width=64 height=48 src=\"https:\/\/steamcdn-a.akamaihd.net\/apps\/730\/icons\/econ\/stickers\/cluj2015\/vp.5cc950372e0c448d2ff958b7ce13fd907bcd2ace.png\"><br>Sticker: pashaBiceps | Cologne 2016, Virtus.Pro | Cluj-Napoca 2015<\/center><\/div>"';
我们已经设法使用
获取img srcpreg_match_all('@src="([^"]+)"@', $string, $matches);
$arr = array_pop($matches);
这将返回一个简单的数组:
[
"https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/cologne2016/sig_pasha.9f41c874350c06e9a902bea06a5228ceccb25ee1.png",
"https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/cluj2015/vp.5cc950372e0c448d2ff958b7ce13fd907bcd2ace.png"
]
我试图让它也显示图像的项目名称,它们只是以逗号分隔,以某种方式得到一个像这样的数组:
[
[
'src' => 'https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/cologne2016/sig_pasha.9f41c874350c06e9a902bea06a5228ceccb25ee1.png',
'name' => 'pashaBiceps | Cologne 2016'
],
[
'src' => 'https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/cluj2015/vp.5cc950372e0c448d2ff958b7ce13fd907bcd2ace.png',
'name' => 'Virtus.Pro | Cluj-Napoca 2015'
[
]
您可以从$string
看到图片也与Stickers:
文字一致,我只是不知道如何让他们合并而不做脏黑客
答案 0 :(得分:1)
这样做的一种方法是:
以下是代码:
// Extract URLs and store them in an array
preg_match_all('@src="([^"]+)"@', $string, $matches);
$matches = array_pop($matches);
// Extract the names as a string and break it down into an array
preg_match('@Sticker\: ([^<]+)<\/center>@', $string, $matches2);
$matches2 = array_pop($matches2);
$matches2 = explode(', ', $matches2);
// Combine the two arrays
$combinedArr = array();
$numItems = count($matches);
for ($i = 0; $i < $numItems; ++$i) {
$combinedArr[] = array('src' => $matches[$i], 'name' => $matches2[$i]);
}
print_r($combinedArr);
$combinedArr
将包含:
Array
(
[0] => Array
(
[src] => https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/cologne2016/sig_pasha.9f41c874350c06e9a902bea06a5228ceccb25ee1.png
[name] => pashaBiceps | Cologne 2016
)
[1] => Array
(
[src] => https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/cluj2015/vp.5cc950372e0c448d2ff958b7ce13fd907bcd2ace.png
[name] => Virtus.Pro | Cluj-Napoca 2015
)
)