PHP regexp用于清除除text-align和color

时间:2017-05-11 13:06:36

标签: php regex

我必须清除所有样式属性,但不能清除文本对齐和颜色 从:

<p style="font-size:14px; font-family:Arial; text-aligh:right; color:#f2f2f2;">TEXT</p>

为:

<p style="text-aligh:right; color:#f2f2f2;">TEXT</p>

1 个答案:

答案 0 :(得分:0)

循环遍历p标记并在节点具有字体样式时更改它们。

$content = '<p style="font-size:14px; font-family:Arial; text-align:right; color:#f2f2f2;">TEXT1</p>';

$dom = new DOMDocument;
$dom->loadHTML($content, LIBXML_HTML_NOIMPLIED);
$nodes = $dom->getElementsByTagName('p');

foreach($nodes as $node)
{
    if ($node->hasAttribute('style'))
    {
        $node->setAttribute('style',preg_replace('/font-.*?;\s*/','',$node->getAttribute('style')));
    }
}

$content = $dom->saveHTML($dom->documentElement);
echo $content, PHP_EOL;