【问题标题】:how to replace and add style into specific tag如何将样式替换并添加到特定标签中
【发布时间】:2015-01-25 15:07:47
【问题描述】:

我有问题。我无法替换和添加内联样式 css。 我有这个 输入:

<p  style="text-align: justify;"><span style="font-size: 11pt;">hello world<br /></span></p>
<p id="tem" style="text-align: justify;">test</p>
<p >&nbsp;</p>
<p>&nbsp;</p>

我想要这个 输出:

<p style="text-align: justify;margin:0;"><span style="font-size: 11pt;">hello world<br /></span></p>
<p id="tem" style="text-align: justify;margin:0;">test</p>
<p  style="margin:0;">&nbsp;</p>
<p style="margin:0;">&nbsp;</p>

我试过这种方式demo

 $re = "/(<p[^>]+\")([^>\"]+)/miu";
    $str = "<p id=\"tem\" style=\"text-align: justify;\"><span style=\"font-size: 11pt;\">hello world<br /></span></p>\n<p style=\"text-align: justify;\">test</p>\n<p >&nbsp;</p>\n<p>&nbsp;</p>";
    $subst = "$1$2margin:0;";

    $result = preg_replace($re, $subst, $str);

请帮助我。谢谢。

【问题讨论】:

  • 你考虑过使用DOM吗?
  • 不,只有 preg_replace。
  • 最后 2 行不匹配且不替换。请看演示
  • 为什么不能自己修改字符串?
  • @self 我不知道高级正则表达式

标签: php regex


【解决方案1】:

我已经解决了:

按正则表达式模式((?&lt;=\&lt;)[^&gt;]+style=")([^&gt;"]+) 搜索并替换为$1$2margin:0;

Live demo

【讨论】:

    猜你喜欢
    • 2013-12-11
    • 1970-01-01
    • 2018-10-15
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多