duanfoumi5620 2016-01-29 10:41
浏览 106

从数组查询结果PHP获取img src

I need to take img src from record after a query:

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
  $rows[] = array(
     'id' => $row['ID_CONTENT'],
     'titolo' => $row['TITOLO'],
     'articolo' => $row['DESCRIZIONE'],
     'giorno' => $row['GIORNO'],
     'foto' => "get img src from this: $row['DESCRIZIONE']",
     'fonte' => $row['FONTE']
);}

Is it possible? I try with preg_match_all('/<img[^>]+>/i',$row['DESCRIZIONE'],$res[0]) but get only 1 as result!

OK I SOLVE SO:

Create a function:

function srcImg($num) {
            preg_match('@src="([^"]+)"@',$num,$match);
            $src = array_pop($match);
            return $src;
         }

and then:

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
  $rows[] = array(
     'id' => $row['ID_CONTENT'],
     'titolo' => $row['TITOLO'],
     'articolo' => $row['DESCRIZIONE'],
     'giorno' => $row['GIORNO'],
     'foto' => srcImg($row['DESCRIZIONE']),
     'fonte' => $row['FONTE']
);}
echo json_encode($rows);
  • 写回答

1条回答 默认 最新

  • duangua5742 2016-01-29 11:18
    关注

    I'd highly recommend what @Javier Núñez suggest, and use an HTML Parser as regex just cannot cover all the eventualities for this. However if for any reason you can't, then you could try using this regex: (untested)

    src=['"]([^"]+)['"]
    

    and you can use that in a preg_match as follows:

    preg_match( '@src=['"]([^"]+)['"]@', $row['DESCRIZIONE'], $match);
    $src = array_pop($match);
    

    You can tinker with that if you need a hacky approach. We all understand the urgency to get something working over a more perfect solution. ;)

    You can use http://regexr.com/ to test your regex if you want to try and make this more robust.

    EDIT: I didn't use preg_match_all. You'll likely want to use that instead.

    评论

报告相同问题?

悬赏问题

  • ¥15 html5+css有人可以帮吗?
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?