【问题标题】:preg_replace and preg_match_all to move img from wordpress $contentpreg_replace 和 preg_match_all 从 wordpress $content 移动图像
【发布时间】:2013-09-26 09:53:21
【问题描述】:

我正在使用preg_replace$content删除某些<img>

$content=preg_replace('/(?!<img.+?id="img_menu".*?\/>)(?!<img.+?id="featured_img".*?\/>)<img.+?\/>/','',$content);

当我现在使用 wordpress the_content 函数显示内容时,我确实从 $content 中删除了 &lt;img&gt;s:

我想事先获取这些图像以将它们放置在模板中的其他位置。我正在使用与preg_match_all 相同的正则表达式模式:

preg_match_all('/(?!<img.+?id="img_menu".*?\/>)(?!<img.+?id="featured_img".*?\/>)<img.+?\/>/', $content, $matches);

但我无法获取我的图片?

preg_match_all('/(?!<img.+?id="img_menu".*?\/>)(?!<img.+?id="featured_img".*?\/>)<img.+?\/>/', $content, $matches);

print_r($matches);

Array ( [0] => Array ( ) ) 

【问题讨论】:

    标签: php regex wordpress preg-replace preg-match-all


    【解决方案1】:

    假设并希望您使用的是 php5,这是 DOMDocument 和 xpath 的任务。带有 html 元素的正则表达式大部分都可以工作,但请查看以下示例 from

    <img alt=">" src="/path.jpg" />
    

    正则表达式将失败。因为在编程中没有太多保证,所以要保证 xpath 会以性能为代价找到你想要的东西,所以要对其进行编码:

    $doc = new DOMDocument();
    $doc->loadHTML('<span><img src="com.png" /><img src="com2.png" /></span>');
    $xpath = new DOMXPath($doc);
    $imgs = $xpath->query('//span/img');
    $html = '';
    foreach($imgs as $img){
      $html .= $doc->saveXML($img);
    }
    

    现在您在$html 中拥有所有img 元素,使用str_replace() 将它们从$content 中删除,然后您可以从那里喝一杯,很高兴带有html 元素的xpath 是无痛的,只是慢了一点

    ps。我懒得理解你的正则表达式,我只是认为 xpath 在你的情况下更好

    【讨论】:

    • 谢谢!看起来不错!我已经解决了我的问题,但下次请记住这一点
    【解决方案2】:

    最后我使用了 preg_replace_callback:

    $content2 = get_the_content();                    
    $removed_imgs = array();                 
    $content2 = preg_replace_callback('#(?!<img.+?id="featured_img".*?\/>)(<img.+? />)#',function($r) {
                        global $removed_imgs;
                        $removed_imgs[] = $r[1];
                        return '';
                    },$content2);
    
    
     foreach($removed_imgs as $img){
                    echo $img;
                 }
    

    【讨论】:

      猜你喜欢
      • 2013-07-17
      • 1970-01-01
      • 2011-08-13
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多