tctc91
tctc91

Reputation: 1363

php str_replace within a CSS file using custom {tags}

I have a script that updates a CSS file based upon some user input from an html form.

The script performs a str_replace and searches the CSS file for "tags". eg-

html,body {
    background: {bgcolor} url(../images/bg.jpg) repeat-x;
    color: {textcolor};
}

This works great but obviously breaks that CSS file. Originally it didn't matter but because of a new feaature in my project, I need to use that CSS file.

So I was wondering if there were any better alternatives to this? I was thinking maybe something like:

html,body {
    background: #fff /*{textcolor*/ url(../images/bg.jpg) repeat-x;
    color: #fff /*{textcolor*/;
}

So I could then use the comment symbols within the tag as well which means my CSS file isn't broken. Only problem is how would I replace/remove the hex as well?

Upvotes: 1

Views: 462

Answers (2)

Robin Castlin
Robin Castlin

Reputation: 10996

With preg_replace():

preg_replace("/\3[\w\d]{3,6}\s\/\*\{textcolor\}\*\//", $str_hex_code, $str_css_file)

Upvotes: 0

user873578
user873578

Reputation:

Presuming that you've already got the script in place which replaces the tags with their respective values, why not do something like this:

1: Create a style.php file which loads style.css

2: style.php uses your already created function to replace the tags with your default values

3: style.php sets the header as header('Content-type: text/css');

4: style.php echoes out the string that has been modified

Then rather than calling style.css throughout your script, call style.php instead.

Upvotes: 2

Related Questions