Php 正则表达式:捕捉图像和锚中的图像

Php 正则表达式:捕捉图像和锚中的图像,php,regex,html-parsing,Php,Regex,Html Parsing,我可以用下面的代码从页面抓取图像,但如何修改它以抓取图像和包装在锚中的图像 $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); $output=preg\u match\u all('//i',$post->post\u content,$matches); 您可以使用类似的方法从字符串中获取整个图像标记或图像名称: $s

我可以用下面的代码从页面抓取图像,但如何修改它以抓取图像和包装在锚中的图像

        $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$output=preg\u match\u all('//i',$post->post\u content,$matches);

您可以使用类似的方法从字符串中获取整个图像标记或图像名称:

$string = '<img src="http://www.google.com/trans.gif">

<a href="http://www.google.com"><img src="http://www.yahoo.com/images/placeholder.gif"></a>';

if (preg_match_all('/<img.*?src=[\'"](.*?)[\'"].*?>/i', $string, $matches)) {
    print "<pre>"; print_r($matches); print "</pre>";
}
else {
    print "Could not find any matches";
}
$string='1!'
';
if(preg_match_all('//i',$string,$matches)){
打印“”;打印($matches);打印“”;
}
否则{
打印“找不到任何匹配项”;
}
这将产生以下结果:

<img   .*?   src=   [\'"]   (.*?)   [\'"]   .*?   >
  ^     ^      ^      ^       ^       ^      ^    ^
  1     2      3      4       5       6      7    8
数组
(
[0]=>阵列
(
[0] => 
[1] => 
)
[1] =>阵列
(
[0] => http://www.google.com/trans.gif
[1] => http://www.yahoo.com/images/placeholder.gif
)
)
正则表达式的解释:


^     ^      ^      ^       ^       ^      ^    ^
1     2      3      4       5       6      7    8
  • ,所以一旦找到它就会停止寻找东西
  • src=
    查找
    src=
    的确切文本
  • [\'”]
    表示匹配单引号或双引号的字符类
  • (.*)
    这与数字2相同,只是我们把它放在括号中,这样我们就可以捕获它找到的任何东西
  • [\'”]
    与数字4相同
  • *?
    与数字2相同
  • 查找大于号的文字(HTML右括号)

  • …您能给出一些您想匹配的示例输入吗。此外,您的正则表达式将从一行的第一个
    开始匹配。如果所有html都在一行上,这是一个问题。同样地,如果有任何换行符,它将完全不匹配。您需要在服务器端这样做吗?我的意思是,如果你是从一个已经发布的网站上抓取这个页面,你是一个“客户”,也许可以用jQuery来代替?
    
    <img   .*?   src=   [\'"]   (.*?)   [\'"]   .*?   >
      ^     ^      ^      ^       ^       ^      ^    ^
      1     2      3      4       5       6      7    8