【问题标题】:PHP to search a css file for a style [duplicate]PHP在css文件中搜索样式[重复]
【发布时间】:2012-11-02 11:02:47
【问题描述】:

可能重复:
Parse a CSS file with PHP

我希望能够在 css 文件中搜索找到类或 id 并恢复其样式。

IE..css 文件布局

body {
margin:0;
padding:0; 
}
span {
margin:0;
padding:0; 
} #input { font:12px arial; }
a { color:#0000FF;
text-decoration:none; 
}
.logout a:hover { text-decoration:underline; }

我想在文件中找到说 id "#input" 并将其带回样式。

font:12px arial;

或 #input{ 字体:12px arial; }

如果有更多的话,很可能会把它带回来,但要保持这个小样。

我尝试了自己,但没有运气,因为我的正则表达式不太好。

if(file_exists("css/style.css") && filesize("css/style.css") > 0){
$filesize = filesize("css/style.css");
$handle = fopen("css/style.css", "r");
$contents = fread($handle, $filesize);
fclose($handle);
}
preg_match('@^(?:#input{)?([^}]+)@i', $contents, $matches);
echo "style: {$matches[0]} <br>";
print_r($matches2);

请帮忙。

【问题讨论】:

  • 它只是带回了这个身体 { margin:0;填充:0;

标签: php css regex


【解决方案1】:

您的特定正则表达式失败有几个原因:

 @^(?:#input{)?([^}]+)@i
  • ^ 标记表示主题的开始。由于您的 #input { CSS 选择器不在正则表达式的开头,所以这总是会失败。

  • 其次,您使用(...)? 将其标记为可选。所以正则表达式无论如何都会忽略寻找#input

  • 那么你也没有转义{

  • 您的实际 CSS 在 #input{ 之间包含一个空格,您的正则表达式没有考虑到该空格。

更正确的是:

@(?:#input\s*\{)([^}]+)@i

另请参阅 Open source RegexBuddy alternativesOnline regex testing 了解一些有用的工具,或参阅 RegExp.info 了解更好的教程。

【讨论】:

  • 谢谢马里奥,我想知道发生了什么,但不知道如何让它工作。但谢谢它的工作原理
  • 好的,那么我将如何去寻找说高度并改变高度的值,所以如果代码是高度:20px;我想将 20px 更改为 10px 说它是 height: 10px;但是值会根据搜索而有所不同,并且更改值也会根据其他一些东西而有所不同。
  • 使用preg_replace_callback 查找{...} 块,然后使用第二个正则表达式height:\s*\d+px 仅使用preg_replace 查找宽度和高度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
  • 2016-04-13
  • 2016-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多