2016-11-23 166 views

回答

1

如果您必须在PHP中操作HTML,那么使用DOM解析器会更安全。作为一个例子,这里是一个基于DOM文档/ DOMXPath获得具有style属性的所有img标签,只有删除这些属性的一些代码:

$html = <<<DATA 
<body> 
<span style="new">Don't modify it</span> 
<span style="old">Don't modify it</span> 
<img style="Remove-me" src="img.jpg"> 
<img src="img.jpg" title="Don't modify it"> 
</body> 
DATA; 

// Initializing the DOM tree with an HTML string above 
$dom = new DOMDocument('1.0', 'UTF-8'); 
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); 

$xpath = new DOMXPath($dom); 
$imgs = $xpath->query('//img[@style]'); // Fetch all img tags having style attribute 

foreach($imgs as $img) { 
    $img->removeAttribute('style'); // Remove the style attribute 
} 

echo $dom->saveHTML(); // Show the modified HTML 

PHP demo

0

你应该反过来做。将样式捕获为第一组并将其替换为无。

$output = preg_replace('/<\s*img[^<>]+?(style\s*=\s*[\'\"][^\'\"]+[\'\"])/i', '', $input);