使用PHP,我如何找到CSS标记/id/class并替换大括号中的样式



我需要遍历一个CSS文件,找到特定的项目,并将它们的CSS更改为主题编辑器的更新内容。我有一个变量,在大括号之间有所有的CSS,我只需要找到一种方法来选择给定标记后的大括号并替换内容。如有任何帮助,我们将不胜感激!感谢

也许不是唯一的解决方案,但您是否想过将CSS放入数据库并动态生成CSS文件?

将其存储在数据库中还可以在每次发生更改时重新生成文件,并将其缓存以节省性能。

要修改现有文件,您可能需要遍历该文件,并希望没有人手动更改CSS文件的样式约定,并通过记住最后一个标记/class/id表达式来替换(可能无法开箱即用!):

$newFileContent = "";
$searchClass = "td.content";
$lines = file("style.css");
$insideSearchedTag = false;
foreach($lines as $line) {
  if (strstr($line, $searchClass) !== false) {
    $insideSearchedTag = true;
    $newFileContent .= "n" . $line;
  }
  else if (strstr($line, "}") !== false) {
    $insideSearchedTag = false;
    $newFileContent .= "n" . $line;
  }
  else if ($insideSearchedTag) {
    // search/replace the content you want to replace.
    $newLineContent = str_ireplace($searchStyle, $replaceStyle, $line);
    $newFileContent .= "n" . $newLineContent;
  }
  else { $newFileContent .= "n" . $line; }
}
fwrite($file, $newFileContent);

最新更新