2012-07-12 51 views
0

我有中有多个图像(有时是一个,有时是两个,有时三)的博客条目中的所有图像,看起来有点像这样:如何使用preg_match_all获得职位的

<a href="http://xxx/" rel="attachment w133> 
    <img class="yyy" title="title1" src="http://xxx/title1.jpg" alt="" width="650" height="487" /> 
</a> 
<a href="http://xxx/" rel="attachment w134"> 
    <img class="yyy" title="title2" src="http://xxx/title2.jpg" alt="" width="650" height="487" /> 
</a> 
<a href="http://xxx/" rel="attachment w135"> 
    <img class="yyy" title="title3" src="http://xxx/title3.jpg" alt="" width="650" height="487" /> 
</a> 

与以下是一些文字。

现在,我想知道如何使用preg_match_all来提取第一部分。我现在有些关于PHP编程,但从未使用过preg_match_all。

这这里的代码确实只能提取过去的形象,这是不够的:

$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_content, $matches); 

这将是巨大的,如果有人可以给我一个提示如何实现这一目标,如果它是不可能的。非常感谢!

+0

的。将匹配任何字符,所以请尝试使用[^ <>],以便它保留在图像标签内 – Waygood 2012-07-12 14:33:33

+0

您可能会更喜欢使用[HTML解析器](http://us2.php.net/manual/en/class)。 domdocument.php)而不是正则表达式。然后,您可以使用XPath查询获取图像。 – Wiseguy 2012-07-12 14:34:00

+0

@Waygood。谢谢。也许如果我使用这样的东西:('/ ')它会提取的东西? – luftikus143 2012-07-12 19:49:09

回答

3
$post_content='<a href="http://xxx/" rel="attachment w133> 
    <img class="yyy" title="title1" src="http://xxx/title1.jpg" alt="" width="650" height="487" /> 
</a> 
<a href="http://xxx/" rel="attachment w134"> 
    <img class="yyy" title="title2" src="http://xxx/title2.jpg" alt="" width="650" height="487" /> 
</a> 
<a href="http://xxx/" rel="attachment w135"> 
    <img class="yyy" title="title3" src="http://xxx/title3.jpg" alt="" width="650" height="487" /> 
</a> 
'; 

preg_match_all('/<a\s[^>]*href=([\"\']??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/siU', $post_content, $matches); 
//print_r ($matches);//$matches - array which contains all your images 
print $matches[0][0]; //first link with image 
print $matches[0][1]; //second link with image 
print $matches[0][2]; //third link with image 

输出:

<a href="http://xxx/" rel="attachment w133&gt; 
    &lt;img class=" yyy"="" title="title1" src="http://xxx/title1.jpg" alt="" width="650" height="487"> 
</a> 
<a href="http://xxx/" rel="attachment w134"> 
    <img class="yyy" title="title2" src="http://xxx/title2.jpg" alt="" width="650" height="487"> 
</a> 
<a href="http://xxx/" rel="attachment w135"> 
    <img class="yyy" title="title3" src="http://xxx/title3.jpg" alt="" width="650" height="487"> 
</a> 
+0

这与上述相同,我提到的那个,不是吗?它导致这样的: 阵列 ( [0] =>数组 ( [0] => ) [1] =>数组 ( [0] => HTTP:// xxx/title2.jpg ) – luftikus143 2012-07-12 19:42:52

+0

这不正是我想要的,因为它只需要最后一张图片,然后它也没有得到既不知道我是否需要他们 – luftikus143 2012-07-12 19:45:36

+0

我编辑了我的答案,现在它做你想要的 – Alex 2012-07-16 07:49:52

0

尝试:

preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"][^\/>]*>/Ui', $post_content, $matches); 
print_r($matches); 
+1

此结果仅适用于:“Array([0] => Array()[1] => Array())” – luftikus143 2012-07-12 19:37:50

相关问题