正規表現は、さまざまなタスクに適していますが、通常、HTML DOMを解析するときに失敗します。 HTMLの問題は、文書の構造が非常に可変であるため、タグを正確に抽出することが難しいことです。あなたも同じように、画像のalt属性を取得することができます
$html = 'Lorem ipsum <img rel="lorem" src="lorem.jpg"/> dolor sit amet, consectetuer <img src="ipsu.jpg" rel="ipsum"/ > ';
$first_image_source = get_first_image($html);
echo $first_image_source;
function get_first_image($html){
require_once('simple_html_dom.php');
$post_dom = str_get_html($html);
$first_img = $post_dom->find('img', 0);
if($first_img !== null) {
return $first_img->src;
}
return null;
}
:
私たちは、あなたが好きそれを使用することができ、そのようなSimpleHTML
としてDOMパーサを使用することができます。あなたはすべての画像のソースを取得したい場合は
、あなたが使用することができます。このことができます
function get_images($html){
require_once('simple_html_dom.php')
$post_dom = str_get_html($html);
$img_tags = $post_dom->find('img');
$images = array();
foreach($img_tags as $image) {
$images[] = $image->src;
}
return $images;
}
希望:) :)
可能な重複:http://stackoverflow.com/questions/3577641/how-to-parse-and-process-html-with-php – cspray