【问题标题】:php remove all css display none from string [closed]php从字符串中删除所有css显示不显示[关闭]
【发布时间】:2016-03-03 13:37:25
【问题描述】:

我有一串包含css的html,类似这样:

<div style="display: none; someotherstyle: freaky; etc ...">
    Some Content
</div>

我想在 PHP 中处理字符串以删除 display: none; 的所有实例

但我还想补偿诸如区分大小写、组件之间的空格(例如display : none ;)和省略尾随分号(即display:none)等差异

感谢您的任何建议!

【问题讨论】:

  • 替换后的示例字符串是什么样的?
  • ...谢谢 :)

标签: php html css regex


【解决方案1】:

您可以使用 sed 来做到这一点。

sed "s/display\s*:\s*none\s*;\?\s*//ig" test.txt

【讨论】:

  • 该问题询问如何使用 PHP 代码处理字符串 - 我觉得针对此调整此答案可能会有所帮助。
  • 请注意,\? 通常表示文字问号。这就是 sed 期望量词的方式吗?
【解决方案2】:

使用解析器可能会更安全,尽管您仍然需要正则表达式来查找样式属性中的特定值。这是一个起点。

$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 是水平空格。
* 是量词,表示前一个字符出现零次或多次。 (在这种情况下是空格)
/s 是 delimiters,它们告诉正则表达式它从哪里开始和结束。
? 使前面的字符/组成为可选的。

Regex101 演示:https://regex101.com/r/cE1pC6/1

正如您将在输出中注意到的那样,它不会删除任何包含display: none(带有可选位)的父级。例如,(eg. ) 被留下,但 display: none ; 消失了。

imodifier 可以添加在结束分隔符之后,因此表达式不区分大小写。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-22
    • 2013-12-30
    • 2011-11-29
    • 2023-04-03
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多