在此示例中,我想将 SRC 属性放入变量中:
<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />
举个例子 - 我想得到一个变量
$foo = "/images/image.jpg"
。
重要的! src 属性将是dynamic,因此不能对其进行硬编码。
有什么快速简便的方法可以做到这一点吗?
谢谢!
编辑:图像将是一个巨大字符串的一部分,该字符串基本上是新闻故事的内容。所以图像只是其中的一部分。
EDIT2:这个字符串中会有更多图像,我只想获取第一个图像的src。这可能吗?
使用像
DOMDocument
这样的 HTML 解析器,然后使用 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"
或者对于那些真正需要节省空间的人:
$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");
对于那些俏皮话:
$src = (string) reset(simplexml_import_dom(DOMDocument::loadHTML($html))->xpath("//img/@src"));
您最好使用 DOM 解析器来进行这种 HTML 解析。考虑这段代码:
$html = '<img id="12" border="0" src="/images/image.jpg"
alt="Image" width="100" height="100" />';
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html); // loads your html
$xpath = new DOMXPath($doc);
$nodelist = $xpath->query("//img"); // find your image
$node = $nodelist->item(0); // gets the 1st image
$value = $node->attributes->getNamedItem('src')->nodeValue;
echo "src=$value\n"; // prints src of image
输出:
src=/images/image.jpg
我用更简单的方法做到了这一点,虽然没有应有的那么干净,但这是一个快速的技巧
$htmlContent = file_get_contents('pageURL');
// read all image tags into an array
preg_match_all('/<img[^>]+>/i',$htmlContent, $imgTags);
for ($i = 0; $i < count($imgTags[0]); $i++) {
// get the source string
preg_match('/src="([^"]+)/i',$imgTags[0][$i], $imgage);
// remove opening 'src=' tag, can`t get the regex right
$origImageSrc[] = str_ireplace( 'src="', '', $imgage[0]);
}
// will output all your img src's within the html string
print_r($origImageSrc);
我知道人们说你不应该使用正则表达式来解析 HTML,但在这种情况下我发现它完全没问题。
$string = '<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />';
preg_match('/<img(.*)src(.*)=(.*)"(.*)"/U', $string, $result);
$foo = array_pop($result);
$imgTag = <<< LOB
<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />
<img border="0" src="/images/not_match_image.jpg" alt="Image" width="100" height="100" />
LOB;
preg_match('%<img.*?src=["\'](.*?)["\'].*?/>%i', $imgTag, $matches);
$imgSrc = $matches[1];
注意: 您应该使用 HTML 解析器,例如
DOMDocument
和 NOT 正则表达式。
$str = '<img border="0" src=\'/images/image.jpg\' alt="Image" width="100" height="100"/>';
preg_match('/(src=["\'](.*?)["\'])/', $str, $match); //find src="X" or src='X'
$split = preg_split('/["\']/', $match[0]); // split by quotes
$src = $split[1]; // X between quotes
echo $src;
其他正则表达式可用于确定拉出的 src 标签是否是图片,如下所示:
if(preg_match('/([jpg]{3}$)|([gif]{3}$)|([jpeg]{3}$)|([bmp]{3}$)|([png]{3}$)/', $src) == 1) {
//its an image
}
可能有两种简单的解决方案: