4
回答
求个获取CSS内容的正则表达式
利用AWS快速构建适用于生产的无服务器应用程序,免费试用12个月>>>   
td{
font-size: 17px;
}
.yessim{
font-size:60px;
color:rgb(196,14,196);

}

像如上的CSS内容,如何用正则匹配到每个属性的值?

PHP
举报
BigZ
发帖于3年前 4回/397阅
共有4个答案 最后回答: 3年前
var 
	css = 'td{ font-size: 17px; } .yessim{ font-size:60px; color:rgb(196,14,196);}',
	reg = /([^\s]+)\s?:\s?([^\{\}\;]+);/g,
	arr = [];
var _i  = 0;
while( (arr = reg.exec(css)) != null ) {
	console.log(arr[0] + '[%c' + arr[1] + ':%c' + arr[2] + '%c]', 'color: red;', 'color: green;', 'color: blank;');
	_i ++;
}

console.log(_i);



<?php
// $css = file_get_contents('test.css');
$css = 'td{ 
font-size: 17px; 
}
.yessim{ 
font-size:60px; 
color:rgb(196,14,196); 
}
';
function css2arr($css){
	$css = str_replace(array("\n","\t","\r"),"",$css);
	$css = preg_replace("/\/\*(.*?)\*\//","",$css);
	$block = explode("}",$css);
	$block = array_filter($block);
	$cssArr = array();
	foreach ($block as $key => $value) {
		$block2 = explode("{",$value);
		$line = explode(";",$block2[1]);
		$line = array_filter($line);
		$lineArr = array();
		foreach ($line as $key2 => $value2) {
			$line = explode(":",$value2);
			$lineArr[trim($line[0])] = trim($line[1]);
		}
		$lineArr = array_filter($lineArr);
		$block2[0] = trim($block2[0]);
		if($cssArr[$block2[0]]){
			$cssArr[$block2[0]] = array_merge($cssArr[$block2[0]],$lineArr);
		}else{
			$cssArr[$block2[0]]= $lineArr;
		}
	}
	return $cssArr;
}
echo $css;
print_r(css2arr($css));

执行效果 

望采纳

顶部