pan*_*ngi 49 html php variables image src
我希望在此示例中将SRC属性转换为变量:
<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />
Run Code Online (Sandbox Code Playgroud)
所以例如 - 我想得到一个变量$foo = "/images/image.jpg".重要!src属性将是动态的,因此不能进行硬编码.有没有快速简便的方法来做到这一点?
谢谢!
编辑:图像将是一个巨大的字符串的一部分,基本上是新闻故事的内容.所以图像只是其中的一部分.
EDIT2:这个字符串中会有更多的图像,我只想获得第一个的src.这可能吗?
hak*_*kre 100
使用类似的HTML解析器DOMDocument,然后评估您要查找的值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"
Run Code Online (Sandbox Code Playgroud)
或者对于那些真正需要节省空间的人:
$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");
Run Code Online (Sandbox Code Playgroud)
对于那里的单线:
$src = (string) reset(simplexml_import_dom(DOMDocument::loadHTML($html))->xpath("//img/@src"));
Run Code Online (Sandbox Code Playgroud)
anu*_*ava 21
最好使用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
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
src=/images/image.jpg
Run Code Online (Sandbox Code Playgroud)
小智 14
我已经采用了更简单的方式,而不是它应该是干净的,但这是一个快速的黑客
$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);
Run Code Online (Sandbox Code Playgroud)
kba*_*kba 11
我知道有人说你不应该使用正则表达式来解析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);
Run Code Online (Sandbox Code Playgroud)
$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];
Run Code Online (Sandbox Code Playgroud)
注意:您应该使用HTML解析器,DOMDocument而不是 regex。