Byte Bit
Byte Bit

Reputation: 513

Removing background-color with php

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!&nbsp;<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

Answers (2)

Glavić
Glavić

Reputation: 43572

Code:

$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;

Output:

<span style="color: red; font: Arial;">text</span>

Upvotes: 0

Rottingham
Rottingham

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

Related Questions