2013-09-26 57 views
0

的img我使用preg_replace$content某些<img>刪除:

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

當我現在顯示使用WordPress的the_content功能的內容,我確實刪除<img>小號從$content

我想事先獲取此圖像將它們放在模板中的其他地方。我使用與preg_match_all相同的正則表達式模式:

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

但我不能讓我的IMGS?

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

print_r($matches); 

Array ([0] => Array ()) 

回答

0

末我已經使用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; 
      } 
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中刪除它們,從那裏你可以喝一杯,並且很高興xpath與html元素是無痛的,只是慢一點點

ps。我想不出有麻煩了解你的正則表達式,我只是覺得XPath是在您的情況

+0

的感謝!那看起來很棒!我已經解決了我的問題,但請記住下次 – Matoeil