如何使用 php 在字符串中搜索 src 和 srcset 标签?
How to search src and srcset tag in string using php?
如何使用 php 在字符串中搜索 src
和 srcset
标签?
通常我使用此代码在 $source
字符串
中搜索 src
标签
preg_match_all('/< *img[^>]*src *= *["\']?([^"\']*)/i', $source, $output);
$src_tag_length = count($output[0]);
然后我想使用 php 在 $source
字符串中搜索 src
和 srcset
标签。
我该怎么做?
preg_match_all('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', $source, $output);
$src_srcset_tag_length = count($output[0]);
我不会为此使用正则表达式,因为众所周知它容易出现用户错误。
您可以并且应该使用PHP的DOMDocument class:
<?php
$html = '<html><body><img src="somethign.jpg"><img srcset="another.jpg"></body></html>';
$dom = new DOMDocument();
$dom->loadHTML( $html );
echo '<pre>';
foreach( $dom->getElementsByTagName( 'img' ) as $node )
{
// Take notice that some img's src and srcset is not set
// but getAttribute() still returns an empty string
var_dump( $node->getAttribute( 'src' ) );
var_dump( $node->getAttribute( 'srcset' ) );
}
如何使用 php 在字符串中搜索 src
和 srcset
标签?
通常我使用此代码在 $source
字符串
src
标签
preg_match_all('/< *img[^>]*src *= *["\']?([^"\']*)/i', $source, $output);
$src_tag_length = count($output[0]);
然后我想使用 php 在 $source
字符串中搜索 src
和 srcset
标签。
我该怎么做?
preg_match_all('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', $source, $output);
$src_srcset_tag_length = count($output[0]);
我不会为此使用正则表达式,因为众所周知它容易出现用户错误。
您可以并且应该使用PHP的DOMDocument class:
<?php
$html = '<html><body><img src="somethign.jpg"><img srcset="another.jpg"></body></html>';
$dom = new DOMDocument();
$dom->loadHTML( $html );
echo '<pre>';
foreach( $dom->getElementsByTagName( 'img' ) as $node )
{
// Take notice that some img's src and srcset is not set
// but getAttribute() still returns an empty string
var_dump( $node->getAttribute( 'src' ) );
var_dump( $node->getAttribute( 'srcset' ) );
}