关闭img后全部匹配


Preg match all after closing img

我在wordpress上遇到了一个小问题;我想要实现的是将我在博客文章中的第一个图像移到div的顶部,并将内容移到其他地方。我当前的脚本如下:

$recent_posts = wp_get_recent_posts($args);
foreach( $recent_posts as $recent ){
$author = get_the_author(); 
echo '<div class="col-md-4 col-lg-4 blog" ><div class="inner">';
preg_match_all("/(<img [^>]*>)/",$recent["post_content"],$img,PREG_PATTERN_ORDER);
    echo $img[1][0];    
echo '<h3><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a></h3> ';
echo '<h6>' . $author . '</h6>';
preg_match_all("/<p>(.*?)<'/p>/s",$recent["post_content"],$content,PREG_PATTERN_ORDER);
echo '<p>';
    echo $content[1][0];
echo '</p>';    
 echo '</div>';
echo '</div>;
}

相反,我想使用一个preg_match_all,第一个数组将选择我的整个第一个img标记,第二个数组将选中之后的所有文本。我怎样才能达到这个结果?

$recent["post_content"]的当前输出为:

   <img src="">
   <p>my content</p> 

我想要的输出是:

 <img src="">
  $title
  $author
<p>my content</p>

致以亲切的问候。

我就是这样做的:构建帖子,然后使用preg_replace提取图像并将其放在帖子的开头。

foreach( $recent_posts as $recent ){
    $author = get_the_author(); 
    echo '<div class="col-md-4 col-lg-4 blog" ><div class="inner">';
    #construct the post
    $post = '<h3><a href="' . get_permalink($recent["ID"]) 
    . '">' . $recent["post_title"].'</a></h3>'
    .'<h6>' . $author . '</h6>';
    . $recent["post_content"];
    # run the replacement:
    echo preg_replace("#(.*?)(<img[^>]+>)#s", "$2$1", $post);
    echo '</div></div>';
}

正则表达式查找第一个img标记,获取它并用它之前的任何内容切换它的位置

示例:将$post设置为

$post = '<h3><a href="my link">title</a></h3>
<h6>author</h6><p>my content here</p>
<p>my content here</p>
<p>my content here</p>
<p>my content here</p>
<img src="img_dir/img.jpg" />
<p>my content here</p>
<p>my content here</p>';

输出:

<img src="img_dir/img.jpg" /><h3><a href="my link">title</a></h3>
<h6>author</h6><p>my content here</p>
<p>my content here</p>
<p>my content here</p>
<p>my content here</p>
<p>my content here</p>
<p>my content here</p>