我正在尝试从PHP中的img标记获取图像地址。这是一个HTML页面:
<div class="image">
<a href="http://mywebpage.com/">
<img height="317" width="214" alt="Photo" title="Photo" src="http://mydomain.com/image.jpg" itemprop="image">
</a>
</div>
PHP部分:
$text = file_get_contents("http://www.mydomain.com/page.html");
//i Tried This One:
preg_match_all('/<div class=\"image\">(.*?)<\/div>/s', $text, $out);
//And This one
preg_match('/~src="(.*)"itemprop="image" \/>/',$text,$out);
//Print
print_r($out);
问题是,我无法仅获取图像地址!我在Google和Stack Overflow中搜索并尝试了一些代码。
我希望你们帮我解决这个问题。
答案 0 :(得分:1)
First download simple_html_dom
from URL:
http://sourceforge.net/projects/simplehtmldom/
Then you find a file "simple_html_dom.php"
Create a file "getImageSrc.php" and include file "simple_html_dom.php"
Write code bellow in getImageSrc.php :
<?php
$url = "www.yoururl.com"; //
$html = file_get_html($url);
foreach($html->find('img') as $e) {
echo $e->src; //img src will be print. you can match your src which you want.
echo "<br />";
}
答案 1 :(得分:1)
你的第二种模式是造成问题的模式:
preg_match('/~src="(.*)"itemprop="image" \/>/',$text,$out);
^ ^^ ^^^
1 2 3
好像是一个流浪的波浪号。要么使用波浪号,要么使用正斜杠作为分隔符。由于我们在文本中有相当多的正斜杠来匹配,我建议使用代字号。
文本中有空格,但正则表达式中没有空格。也许请使用\s*
以防万一。
文中没有类似的内容。虽然以防万一可能存在字符,但您可以使用[^>]*
,这意味着任何字符不是>
0次或更多次。
应用这三个,我们得到:
preg_match('~src="(.*)"\s*itemprop="image"[^>]*>~',$text,$out);
答案 2 :(得分:0)
preg_match('/<img.*? src=\"(.*?)\".*?>/',$text,$out);
它对我有用。试试这个解决方案
答案 3 :(得分:0)
试试这个
preg_match('/src="(.*?)" itemprop="image"/',$text,$match);
print_r("match=>".$match[1]);