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);
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.