php 从字符串中删除所有 css 显示无

标签 php html css regex

<分区>

我有一串包含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/

相关文章:

php - 计算组连续行中的状态数

jquery - 如何使用 HTML5 Canvas 复制 'skid marks'?

php - 如何使用 behat 检查标题标签的内容?

php - Laravel 5.4 关系不起作用无法附加第二个参数

php - 如何获取特定命名空间内的所有类名?

html - 按钮和文本距离太远

html - 文章底部的文字

css - 如何根据内容创建高度可变的全宽背景图像?

css - 从 bootstrap 3.3.7 到 bootstrap 4.1.3

php - 具有特定条件的 LEFT JOIN