PHP使用preg_match_all获取所有链接和图像

PHP使用preg_match_all获取所有链接和图像,php,preg-match-all,Php,Preg Match All,在新闻网站上,我们有许多标签,如: <a class="picLink" target="_blank" href="/EN/news/397423/MY-TEST-NEWS"> <img class="fr" width="115" style="margin:6px 0px 0px 8px;width: 115px;" src="http://sample.com/files/EN/news/369326_276.jpg" alt="MY TEST NEWS !"&g

在新闻网站上,我们有许多标签,如:

<a class="picLink" target="_blank" href="/EN/news/397423/MY-TEST-NEWS">
   <img class="fr" width="115" style="margin:6px 0px 0px 8px;width: 115px;" src="http://sample.com/files/EN/news/369326_276.jpg" alt="MY TEST NEWS !">
</a>

请帮我纠正一下。

你可以用这个来得到它

$re = '/(alt|href|src)=("[^"]*")/'; 
$str = '<a class="picLink" target="_blank" href="/EN/news/397423/MY-TEST-NEWS">\n   <img class="fr" width="115" style="margin:6px 0px 0px 8px;width: 115px;" src="http://sample.com/files/EN/news/369326_276.jpg" alt="MY TEST NEWS !">\n</a>\n<a class="picLink" target="_blank" href="/EN/news/397423/MY-TEST-NEWS">\n   <img class="fr" width="115" style="margin:6px 0px 0px 8px;width: 115px;" src="http://sample.com/files/EN/news/369326_276.jpg" alt="MY TEST NEWS !">\n</a>'; 

preg_match_all($re, $str, $matches);
print_r($matches);

在数组[2]中,您将获得所需的值

$re = '/(alt|href|src)=("[^"]*")/'; 
$str = '<a class="picLink" target="_blank" href="/EN/news/397423/MY-TEST-NEWS">\n   <img class="fr" width="115" style="margin:6px 0px 0px 8px;width: 115px;" src="http://sample.com/files/EN/news/369326_276.jpg" alt="MY TEST NEWS !">\n</a>\n<a class="picLink" target="_blank" href="/EN/news/397423/MY-TEST-NEWS">\n   <img class="fr" width="115" style="margin:6px 0px 0px 8px;width: 115px;" src="http://sample.com/files/EN/news/369326_276.jpg" alt="MY TEST NEWS !">\n</a>'; 

preg_match_all($re, $str, $matches);
print_r($matches);

在数组[2]中,您将获得所需的值

人们总是说,不要使用正则表达式解析HTML。有时候人们是对的。不要使用正则表达式。使用dom解析器:是否需要使用REGEXP?如果不是人们总是说,不要使用正则表达式解析HTML,我可能会有一些更简单的解决方案。有时候人们是对的。不要使用正则表达式。使用dom解析器:是否需要使用REGEXP?如果不是的话,我可能有一些更简单的解决方案。为什么在捕获组中使用引号?为什么在捕获组中使用引号?
(
    [0] => Array
        (
            [0] => href="/EN/news/397423/MY-TEST-NEWS"
            [1] => src="http://sample.com/files/EN/news/369326_276.jpg"
            [2] => alt="MY TEST NEWS !"
            [3] => href="/EN/news/397423/MY-TEST-NEWS"
            [4] => src="http://sample.com/files/EN/news/369326_276.jpg"
            [5] => alt="MY TEST NEWS !"
        )

    [1] => Array
        (
            [0] => href
            [1] => src
            [2] => alt
            [3] => href
            [4] => src
            [5] => alt
        )

    [2] => Array
        (
            [0] => "/EN/news/397423/MY-TEST-NEWS"
            [1] => "http://sample.com/files/EN/news/369326_276.jpg"
            [2] => "MY TEST NEWS !"
            [3] => "/EN/news/397423/MY-TEST-NEWS"
            [4] => "http://sample.com/files/EN/news/369326_276.jpg"
            [5] => "MY TEST NEWS !"
        )

)