将2 preg_match_all合并在一起

时间:2018-03-22 02:12:15

标签: php preg-match-all

我正试图找到这个名字&来自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 src
preg_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:文字一致,我只是不知道如何让他们合并而不做黑客

1 个答案:

答案 0 :(得分:1)

这样做的一种方法是:

  1. 将字符串分别提取为字符串
  2. 将此字符串分解为数组
  3. 解析src并命名数组并将值推送到组合数组中。
  4. 以下是代码:

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