我正在用str_replace清理CSS输出,但需要忽略定义了开始和结束的某些字符串块。
忽略所有以:开头的内容:
@media blah(this can be any value) {要忽略的内容:
.class {
property: value;
}并以:
}/*ends*/并在该块之外执行str_replace:
.otherclass {property:value;}PHP:
$output = str_replace("{", "{\n", $output);
$output = str_replace("}", "}\n", $output);原因是@media块需要已经正确格式化的适当缩进,并且不应该被简单地返回可读行的str_replace所触及:
.otherclass {
property:value;
}用PHP怎么说呢?
谢谢
发布于 2012-04-24 13:51:46
$string =
"@media blah(this can be any value) {
.class {
property: value;
}
}/*ends*/
.otherclass {property:value;}
.otherclass {property:value;}
@media blah(this can be any value) {
.class {
property: value;
}
}/*ends*/
.otherclass {property:value;}
.otherclass {property:value;}";
$arr = explode("\r", $string);
$ignore_block = false;
for ($i = 0; $i < count($arr); $i++)
{
if (strstr($arr[$i], '@media'))
$ignore_block = true;
elseif (strstr($arr[$i-1], '/*ends*/'))
$ignore_block = false;
if ($ignore_block == false)
{
$arr[$i] = str_replace("{", "{\n\t", $arr[$i]);
$arr[$i] = str_replace("}", "\n}\n", $arr[$i]);
}
}
file_put_contents("test.txt", implode("\n", $arr));正则表达式不能工作,因为lookbehind不允许可变长度。尝试遍历该文件。
发布于 2012-04-24 12:39:09
我也认为正则表达式是最好的选择,因为它们给了你更多的灵活性。
我猜最简单的解决方案是首先从输出源获取所有这些事件,然后对其余代码使用str_replace,然后将其放回原处。我可能还会一行接一行地检查代码,只运行str_replace
同样,您最好的机会是使用正则表达式。你正在寻找的似乎是preg_replace,告诉它不要匹配@media之前的任何内容
参考文献:
发布于 2012-04-24 13:36:20
正则表达式不能计数,所以它们通常不适合解析(这就是您正在做的)。也就是说,除非你能限制输入格式超过有效CSS的全集,否则你可能会发现有些情况不能像预期的那样工作。
您还可以尝试完全解析CSS,并使用规则遍历生成的CSS树,以指定如何输出数据。这里显然有一个CSS解析器库:
http://www.phpclasses.org/package/1289-PHP-CSS-parser-class.html
https://stackoverflow.com/questions/10291595
复制相似问题