【问题标题】:Preg match all after closing img关闭 img 后所有预匹配
【发布时间】:2014-10-28 15:53:50
【问题描述】:

我在使用 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>

亲切的问候。

【问题讨论】:

  • 你能发布你的输入和想要的输出吗?将“内容移到其他地方”有点模糊......你只是想交换图像和第一个&lt;p&gt;吗?
  • 正确,我的输出看起来像

    my content here

    ,我想要实现的是: $title $作者

    我的内容在这里

标签: php html wordpress


【解决方案1】:

这就是我的做法:构建帖子,然后使用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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-20
    • 2020-06-02
    • 2017-05-30
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多