我一直试图找出regex
的错误。
有人可以给我一些指导吗?
请注意,它并不总是<a>
代码或<img>
代码这就是为什么我没有去DOM()
的路线
HTML:
<a href="http://domain.co.uk.co.uk/wp-content/uploads/2016/06/DSCN8900.jpg"><img class="alignnone size-medium wp-image-4181" src="http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900-300x225.jpg" alt="dscn8900" width="300" height="225" srcset="http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900-300x225.jpg 300w, http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900-768x576.jpg 768w, http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900-1024x768.jpg 1024w, http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900-195x146.jpg 195w, http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900-50x38.jpg 50w, http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900-93x70.jpg 93w" sizes="(max-width: 300px) 100vw, 300px"></a>
PREG_MATCH_ALL:
preg_match_all('/(((http|https|ftp|ftps)\:\/\/)|(www\.))[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\:[0-9]+)?(\/\S*)?(\W)/', $HTMLSourceCode, $results, PREG_PATTERN_ORDER);
RESULT
print_r($results[0][0]);
// http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900.jpg">
预期结果:
http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900.jpg
答案 0 :(得分:1)
以下是执行此工作的DOM
示例:
$html = <<<EOF
<a href="http://domain.co.uk.co.uk/wp-content/uploads/2016/06/DSCN8900.jpg">
<img class="alignnone size-medium wp-image-4181" src="http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900-300x225.jpg" alt="dscn8900" width="300" height="225" srcset="http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900-300x225.jpg 300w, http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900-768x576.jpg 768w, http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900-1024x768.jpg 1024w, http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900-195x146.jpg 195w, http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900-50x38.jpg 50w, http://domain.co.uk/wp-content/uploads/2016/06/DSCN8900-93x70.jpg 93w" sizes="(max-width: 300px) 100vw, 300px"></a>
EOF;
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$nodeList = $xpath->query('//a/@href');
echo $nodeList->item(0)->value . "\n";
<强>输出:强>
http://domain.co.uk.co.uk/wp-content/uploads/2016/06/DSCN8900.jpg