如何使用正则表达式将标签html保存到变量

时间:2012-09-30 12:59:11

标签: php regex

我有函数<?php the_content(); ?> wihch生成html标签:

<p>
 <a href="http://127.0.0.1/www/www1/wordpress/wordpressEng/wp-content/uploads/2012/09/page1-img2.jpg">
  <img class="alignnone size-full wp-image-82" title="page1-img2" src="http://127.0.0.1/www/www1/wordpress/wordpressEng/wp-content/uploads/2012/09/page1-img2.jpg" alt="" width="219" height="124" />
 </a>
</p> 

我尝试提取<img.**./>,但我没有提及。

像:

//$String =
<p>
 <a href="http://127.0.0.1/www/www1/wordpress/wordpressEng/wp-content/uploads/2012/09/page1-img2.jpg">
  <img class="alignnone size-full wp-image-82" title="page1-img2" src="http://127.0.0.1/www/www1/wordpress/wordpressEng/wp-content/uploads/2012/09/page1-img2.jpg" alt="" width="219" height="124" />
 </a>
</p> 

$String = "the_content()";

$pattern = '/^<img/.*/$/>/';//Take string wich start with "<img" and all between and End in "/>"
preg_match($pattern, substr($subject,3), $StrImg, PREG_OFFSET_CAPTURE);
echo $StrImg[0];
output
//<img class="alignnone size-full wp-image-82" title="page1-img2" src="http://127.0.0.1/www/www1/wordpress/wordpressEng/wp-content/uploads/2012/09/page1-img2.jpg" alt="" width="219" height="124" />

如何设置变量$StrImg完整的img标记?

非常感谢。

1 个答案:

答案 0 :(得分:3)

所以你想获得你发布的所有图像的src属性。有更简单的方法:

$images = get_posts(array(
            'post_parent' => $post->ID,
            'post_type' => 'attachment',
            'numberposts' => -1,
            'post_mime_type' => 'image'
        ))

        foreach( $images as $image ) {
            $image_url[] = wp_get_attachment_image_src( $image->ID, full );

        }