Reputation: 513
I'm trying to remove the background-color from a string with PHP, and for that I want to use a regular expression (which is, in my opinion, the fastest way to achieve that).
Here's what I have:
<span style="font-family: Arial, Narrow, sans-serif; background-color: rgb(25, 56, 92); color: rgb(170, 170, 170);">Parabéns! Você recebeu um pouco de sorte! <br></span>
I simply want to remove "background-color: {color value}" from the style attribute. However, backgrounds can have different colors, and it can be either hexadecimal or RGB() (In this case).
Here's the expression I have created, which didn't work, unfortunately:
/background-color: ?(\#[a-fA-F0-9]{3,6}|rgb\([0-9]{2,3},[0-9]{2,3},[0-9]{2,3}\))\;/
I tryed to search over the web and in stackoverflow, but I couldn't find an answer to this specific problem.
Thanks for your attention.
Upvotes: 0
Views: 1328
Reputation: 43572
$s = '<span style="color: red; background-color: #fff; background-color: rgb(25, 56, 92); font: Arial;">text</span>';
$s = preg_replace('~background-color:.+?;\s*~', '', $s);
echo $s;
<span style="color: red; font: Arial;">text</span>
Upvotes: 0
Reputation: 2604
Use preg_replace() and regular expressions.
$string = "background-color: #ffffff;";
$expression = "/background-color:(.*?);/";
$string = preg_replace($expression, '', $string);
var_dump($string);
Outputs:
string '' (length=0)
Yes, this will get rid of your string with the rgb(...) value. It matches anything between background-color: and the semicolon.
Recognize the limitation to this however. it will only replace
background-color: value;
If the HTML code perhaps uses background: #ffffff it will fail.
Upvotes: 1