miki
miki

Reputation: 33

RegEx to remove background color and color property but leave all styles in php

I am still not able to use regular expressions by heart, thus could not find a final solution to strip out background color,font-family and color property from table with RegEx, but leave all styles

I have tried regular expression to remove all styles except color and background property. But actually I want to remove background color,font-family and color property but leave all styles

if(isset($_REQUEST["Save"])) {
    $VariantName = $_REQUEST["name"];
    $desc = preg_replace('/(<[^>]+\s+)(?:style\s*=\s*"(?!(?:|[^"]*[;\s])color\s*:[^";]*)(?!(?:|[^"]*[;\s])background-color\s*:[^";]*)[^"]*"|(style\s*=\s*")(?=(?:|[^"]*[;\s])(color\s*:[^";]*))?(?=(?:|[^"]*)(;))?(?=(?:|[^"]*[;\s])(background-color\s*:[^";]*))?[^"]*("))/i', '', $VariantName);
    echo $desc;
}

This

<p style="font-family:Garamond;font-size:8px;line-height:14px;color:#FF0000;background-color:red;">example</p>

should become:

<p style="font-size:8px;line-height:14px;">example</p>

Upvotes: 3

Views: 1169

Answers (1)

Aziz.G
Aziz.G

Reputation: 3721

I don't recommend this but you can use this regular expression to remove the CSS props you want:

/(background-color|color|font-family)\:\#?\w+\;/i

Example:

<?php
            //Enter your code here, enjoy!
    $string = '<p style="font-family:Garamond;font-size:8px;line-height:14px;color:#FF0000;background-color:red;">example</p>';
    $pattern = '/(background-color|color|font-family)\:\#?\w+\;/i';
    $replacement = '';
    echo preg_replace($pattern, $replacement, $string);

Upvotes: 1

Related Questions