0
$img = '<img src="http://some-img-link" alt="some-img-alt"/>';

$src = preg_match('/<img src=\"(.*?)\">/', $img);

echo $src;

我想src从 img 标签中获取值,也许是 alt 值

4

9 回答 9

2

假设您总是得到问题中显示的 img html。

现在在正则表达式中,您提供了它的说法,在 src 属性之后,它给出了 img 的结束标记。但在字符串中也有一个 alt 属性。所以你也需要关心它。

/<img src=\"(.*?)\".*\/>/

如果你还要检查 alt 然后是正则表达式。

/<img src=\"(.*?)\"\s*alt=\"(.*?)\"\/>/

另外,您只是在检查其是否匹配。如果您需要获取匹配项,则需要向 preg_match 提供第三个参数,该参数将填充匹配项。

$img = '<img src="http://some-img-link" alt="some-img-alt"/>';
$src = preg_match('/<img src=\"(.*?)\"\s*alt=\"(.*?)\"\/>/', $img, $results);
var_dump($results);

注意:上面给出的正则表达式不是那么通用,如果您可以提供将出现的 img 字符串,将提供更强大的正则表达式。

于 2012-07-10T04:51:29.740 回答
1

测试代码:

$ input=’&lt;img src= ”http://www.site.com/file.png” > ‘;
preg_match(“&lt;img.*?src=[\"\"'](?<url>.*?)[\"\"'].*?>”,$input,$output);
echo $output;   // output = http://www.site.com/file/png
于 2012-12-26T12:50:02.187 回答
1
 function scrapeImage($text) {
    $pattern = '/src=[\'"]?([^\'" >]+)[\'" >]/';
    preg_match($pattern, $text, $link);
    $link = $link[1];
    $link = urldecode($link);
    return $link;

}
于 2012-07-10T06:23:51.827 回答
0

如何使用 php 从 html 中提取 img src、title 和 alt?

请参阅这篇文章的第一个答案。

您将使用 preg_match,只是方式略有不同。

于 2012-07-10T04:10:48.293 回答
0

试试这个代码:

<?php
$doc = new DOMDocument();
$doc->loadHTML('<img src="" />');
$imageTags = $doc->getElementsByTagName('img');

foreach($imageTags as $tag) {
    echo $tag->getAttribute('src');
}
?>
于 2012-07-10T04:15:29.900 回答
0
preg_match('/<img src=\("|')([^\"]+)\("|')[^\>]?>/', $img);
于 2012-07-10T04:20:30.977 回答
0

你也可以使用这个库:SimpleHtmlDom

<?php
$html = new simple_html_dom();
$html->load('<html><body><img src="image/profile.jpg" alt="profile image" /></body></html>');
$imgs = $html->find('img');
foreach($imgs as $img)
print($img->src);
?>
于 2012-07-10T06:21:54.163 回答
0

您在上面已经有足够好的响应,但这里有另一个代码(更通用):

function retrieve_img_src($img) {
  if (preg_match('/<img(\s+?)([^>]*?)src=(\"|\')([^>\\3]*?)\\3([^>]*?)>/is', $img, $m) && isset($m[4]))
    return $m[4];
  return false;
}
于 2015-11-21T04:47:12.937 回答
-2

您可以使用 JQuery 获取 src 和 alt 属性

在标题中包含 jquery

 <script type="text/javascript" 
           src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
 </script>

//HTML

//获取src和alt属性

<script type='text/javascript'>
 // src attribute of first image with id =imgId

 var src1= $('#imgId1').attr('src');
 var alt1= $('#imgId1').attr('alt');

 var src2= $('#imgId2').attr('src');
 var alt2= $('#imgId2').attr('alt');
</script>
于 2012-07-10T04:38:30.867 回答