<分区>
我有一串包含css的html,类似这样:
<div style="display: none; someotherstyle: freaky; etc ...">
Some Content
</div>
我想在 PHP 中处理字符串以删除 display: none;
但我还想弥补差异,例如区分大小写、组件之间的空白(例如 display : none ;
)和省略尾随分号(即 显示:无
)
感谢您的任何建议!
<分区>
我有一串包含css的html,类似这样:
<div style="display: none; someotherstyle: freaky; etc ...">
Some Content
</div>
我想在 PHP 中处理字符串以删除 display: none;
但我还想弥补差异,例如区分大小写、组件之间的空白(例如 display : none ;
)和省略尾随分号(即 显示:无
)
感谢您的任何建议!
最佳答案
使用解析器可能会更安全,尽管您仍然需要一个正则表达式来查找样式属性中的特定值。这是一个起点。
$string = 'But I\'d also like to compensate for discrepancies such as case sensitivity, white space between the components (eg. display : none ;) and omission of the trailing semicolon (ie. display:none)';
echo preg_replace('/display\h*:\h*none\h*;?/', '', $string);
输出:
But I'd also like to compensate for discrepancies such as case sensitivity, white space between the components (eg. ) and omission of the trailing semicolon (ie. )
\h
是水平空格。
*
是一个量词,表示前一个字符出现零次或多次。 (在这种情况下是空格)
/
是 delimiters ,它们告诉正则表达式它的开始和结束位置。
?
使前面的字符/组可选。
Regex101 演示:https://regex101.com/r/cE1pC6/1
正如您将在输出中注意到的那样,它不会删除任何包含 display: none
(带有可选位)的父级。因此,例如 (eg. )
被留下,但 display: none ;
消失了。
i
modifier可以在结束分隔符之后添加,因此表达式不区分大小写。
关于php 从字符串中删除所有 css 显示无,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33989772/