javascript - 如何使用正则表达式选择 CSS 文本?
问题描述
有人可以建议一个正则表达式来选择/分离css规则中的键值对并将它们转换为对象吗?
//css rules
animation-iteration-count: 1; animation-name: none; animation-play-state: running;
进入这个:
{
'animation-iteration-count': 1, 'animation-name': none, 'animation-play-state': running
}
和/或这个:
[
{key: 'animation-iteration-count', value: 1},
{key: 'animation-name', value:none },
{key: 'animation-play-state', value: running },
]
如果可能,首选 REGEX(或者如果没有,则使用 vanilla js)
解决方案
不完全确定您要做什么,但我在 PHP 中编写了以下内容,以便为您提供一个良好的开端:
<?php
function cssJSON($fileName){
$css = preg_replace('/(?<![a-z])\s+|\n+|\r+/i', '', file_get_contents($fileName));
preg_match_all('/[^\/}]+{[^}]+}/', $css, $a); $m = $a[0]; $r = [];
foreach($m as $c){
$o = new StdClass; $q = explode('{', $c); $o->selectors = explode(',', $q[0]); $x = preg_replace('/;*}$/', '', $q[1]); $s = explode(';', $x); $o->style = [];
foreach($s as $c){
$z = explode(':', $c); $w = explode('-', $z[0]); $g = $z[1]; $b = new StdClass;
if(isset($w[1])){
$b->{$w[0].ucfirst($w[1])} = $g;
}
else{
$b->{$w[0]} = $g;
}
$o->style[] = $b;
}
$r[] = $o;
}
return json_encode($r);
}
// usage
$json = cssJSON('css/external.css');
?>
它返回一个对象数组,其中包含一个selectors
字符串数组和一个style
对象数组。绕开!
推荐阅读
- angular - 无法将嵌套表单组绑定到反应表单中的表单数组?
- leaflet - Grafana - 点击阈值时世界地图打开一个网页
- swift - CGSize 不接受 `.zero`。'init(width:height:)' 的模糊使用
- python - 打印 2D NumPy 数组时如何删除外括号
- flutter - 更改格式日期时间
- javascript - 使用 insertAdjacentHTML 会在 .js 文件中出现错误,但在控制台片段中却没有
- javascript - 如何在导航栏外发起点击以将其关闭
- java - 为什么 if 语句“if(1)”在 Java 中会出错,但在 C++ 中却是正确的?
- javascript - 高亮文本字段的逻辑操作
- php - 用PHP生成中间点的分页