doukuiqian5345 2014-10-28 15:53
浏览 29
已采纳

关闭img后Preg匹配所有

I'm having a small issue with wordpress; what i want to achieve is move my first image on a blog post to the top of the div, and the content somewhere else. My current script looks like this:

$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>;
}

Instead i would like to use one preg_match_all, 1st array would select my whole first img tag and the 2nd array would select all the text after that. How can i achieve this result?

My current output from $recent["post_content"] is :

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

What my desired output would be is:

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

Kind regards.

  • 写回答

1条回答 默认 最新

  • dongpan1365 2014-10-28 16:18
    关注

    This is how I'd do it: construct the post, and then use preg_replace to pull out the image and put it at the start of the post.

    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>';
    }
    

    The regex looks for the first img tag, takes it and switches its position with whatever came before it.

    Example: set $post to

    $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>';
    

    Output:

    <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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本