Parsing CSS by regex

前端 未结 8 1763
时光说笑
时光说笑 2020-11-27 17:37

I\'m creating a CSS editor and am trying to create a regular expression that can get data from a CSS document. This regex works if I have one property but I can\'t get it to

8条回答
  •  庸人自扰
    2020-11-27 18:10

    Try this

    function trimStringArray($stringArray){
        $result = array();
        for($i=0; $i < count($stringArray); $i++){
            $trimmed = trim($stringArray[$i]);
            if($trimmed != '') $result[] = $trimmed;
        }
        return $result;
    }
    $regExp = '/\{|\}/';
    $rawCssData = preg_split($regExp, $style);
    
    $cssArray = array();
    for($i=0; $i < count($rawCssData); $i++){
        if($i % 2 == 0){
            $cssStyle['selectors'] = array();
            $selectors = split(',', $rawCssData[$i]);
            $cssStyle['selectors'] = trimStringArray($selectors);
        }
        if($i % 2 == 1){
            $attributes = split(';', $rawCssData[$i]);
            $cssStyle['attributes'] = trimStringArray($attributes);
            $cssArray[] = $cssStyle;
        }
    
    }
    //return false;
    echo '
    '."\n";
    print_r($cssArray);
    echo '
    '."\n";

提交回复
热议问题