1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| $html = <<<'HTML'
<div class="blockImg imgRight">
<img src="customs/2/pictures/home.png">
<figcaption>Une légende</figcaption>
</div>
HTML;
// on ajoute la structure manquante pour préciser l'encodage
$html = <<<HTML
<html><head><meta charset="utf-8"/></head><body>$html</body></html>
HTML;
$dom = new \DOMDocument;
$dom->loadHTML($html, LIBXML_NOERROR);
$context = $dom->getElementsByTagName('div')[0];
$xp = new \DOMXPath($dom);
// on extrait la valeur de l'attribut class tout en vérifiant la présence de la classe "blockImg"
$classAttrValue = $xp->evaluate(
'string(@class[contains(concat(" ", normalize-space(.), " "), " blockImg ")])',
$context
);
if ($classAttrValue && preg_match('~ \b img (?: Right | Left ) \b ~x', $classAttrValue, $m)) {
$class = $m[0];
$src = $xp->evaluate('string(img/@src)', $context);
$filename = basename($src);
$caption = $xp->evaluate('string(figcaption)', $context);
echo $class, PHP_EOL, $src, PHP_EOL, $filename, PHP_EOL, $caption, PHP_EOL;
} |
Partager