So I am building a parser for stylesheets. And in my CSS file, I will parse something like this:
body {
background-image: &gradient(#1073b8, &saturate(#1073b8, -20), 40);
}
The result would be a value of something like this:
body {
background-image: url(/cache/graident12345.png);
}
Which is the output of my &gradient()
function, that I catch and execute. But one of the arguments to &gradient()
is the result of &saturate()
, so it's hierarchical, and I need preg_replace()
to handle them inner to outer, but how do I do that? So first catch and parse &saturate()
, return a color HEX value, which in turn will be in the string when parsing &gradient()
. My current lookup code looks like this:
if (preg_match("/\&(gradient|saturate)\((.*?)\)/", $value, $m)){
$arg = explode(", ", $m[2]); # splits argument to the function
if ($m[1] == "saturate"){
$value = str_replace($m[0], saturate($arg[1], $arg[2]);
}
}
And I'll add functions as I make them available. Alternatively, catch the function name as well in the regexp.
Do I make myself clear? Any ideas? :)
You can do some interesting parsing using regex in combination with a recursive function. I have mocked up something that will work for your scenario, feel free to tweak it to your needs.
If you need any explanation of what is going on, let me know, but it basically creates a recursive structure through a recursive call to a function that regexes for the pattern &functionname([args...])
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.