Use a HTML parser like DOMDocument
and then evaluate the value you're looking for with DOMXpath
:
$html = '<img id="12" border="0" src="/images/image.jpg"
alt="Image" width="100" height="100" />';
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg"
Or for those who really need to save space:
$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");
And for the one-liners out there:
$src = (string) reset(simplexml_import_dom(DOMDocument::loadHTML($html))->xpath("//img/@src"));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…