我正在使用preg_replace
从某些<img>
中删除$content
:
$content=preg_replace('/(?!<img.+?id="img_menu".*?'/>)(?!<img.+?id="featured_img".*?'/>)<img.+?'/>/','',$content);
当我现在使用 wordpress the_content 函数显示内容时,我确实从$content
中删除了<img>
:
我想事先让这些图像将它们放置在模板中的其他地方。我使用相同的正则表达式模式与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 ( ) )
假设并希望您使用的是php5,这是DOMDocument和xpath的任务。 带有 HTML 元素的正则表达式大部分都可以工作,但请查看以下示例
<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 是无痛的,只是慢一点
懒得理解你的正则表达式,我只是认为 xpath 在你的情况下更好
最后我使用了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;
}