PHP中用正则移除style属性除font-family外所有属性的求助
问题原因
你原来的正则存在三个核心问题:
.*是贪婪匹配,会跨标签匹配多个style属性的内容,匹配范围完全超出预期- 没有限定style属性的单/双引号边界,容易出现匹配溢出
- 没有覆盖无font-family的style属性场景,这类属性需要整体删除
修复方案
推荐使用preg_replace_callback处理每个匹配到的style属性,逻辑更清晰也不容易出问题,代码如下:
// 你的原始HTML内容 $sourceHtml = <<<HTML <div style='margin: 0px 14.3906px 0px 28.7969px; padding: 0px; width: 436.797px; float: left; font-family: "Open Sans", Arial, sans-serif;'><p style="margin-right: 0px; margin-bottom: 15px; margin-left: 0px; padding: 0px; text-align: justify;"><strong style="margin: 0px; padding: 0px;">Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p><div><br></div></div><div style='margin: 0px 28.7969px 0px 14.3906px; padding: 0px; width: 436.797px; float: right; font-family: "Open Sans", Arial, sans-serif;'></div> HTML; $processedHtml = preg_replace_callback('/\sstyle=([\'"])(.*?)\1/is', function($matches) { // 提取style中的font-family属性 if (preg_match('/font-family:\s*[^;]+/i', $matches[2], $fontRes)) { return " style={$matches[1]}{$fontRes[0]}{$matches[1]}"; } // 无font-family则直接删除整个style属性 return ''; }, $sourceHtml); echo $processedHtml;
正则说明
- 外层匹配style属性的正则
/\sstyle=([\'"])(.*?)\1/is:\s匹配style属性前的空格,避免匹配到属性名中带style的异常内容([\'"])匹配style属性的单引号或双引号,存入分组1作为边界标识(.*?)非贪婪匹配style属性值,直到遇到和分组1一致的引号就停止,避免跨标签匹配- 修饰符
i忽略大小写匹配,s让.可以匹配换行符
- 内层提取font-family的正则
/font-family:\s*[^;]+/i:- 忽略大小写匹配font-family开头的属性值,直到遇到分号为止,完整提取font-family的配置内容
以上代码运行输出和你给出的预期效果完全一致。
内容的提问来源于stack exchange,提问作者Bhumi Shah
相关产品推荐
相关产品推荐

