1

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);
DigitalXP
  • 179
  • 5
  • 18
  • [seems good](https://3v4l.org/pmOTG) to me. how did you use `$res[0]`? – Federkun Jan 29 '16 at 10:45
  • Possible duplicate of [How to extract img src, title and alt from html using php?](http://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php) – Javier Núñez Jan 29 '16 at 10:47
  • It's not a duplicate! I use $row array to trasform results in json string. So I need to get directly foto = src image – DigitalXP Jan 29 '16 at 11:20

1 Answers1

0

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.

Simon Willan
  • 378
  • 3
  • 14