javascript - 用 PHP 脚本替换 CSS

标签 javascript php css

我正在我的网站中生成 CSS。

使用 JavaScript,我可以生成用户决定的 CSS 代码。

通过单击按钮,新代码将替换旧代码,但我的 PHP 脚本不起作用。

首先,我刚刚在脚本的开头定义了旧变量和新变量。

<?php 

    $fichier='texte.css';
    $backgroundcolor='background-color:yellow;';
    $background='/background-color:blue;/';

    $text=fopen($fichier,'r+') or die("File missing"); 
    $contenu=file_get_contents($fichier);

    /* Open the file and get an array with one line per element*/
    $lines = file($fichier);
    foreach ($lines as $lineNumber => $lineContent)
    {
        echo ("$lineNumber $lineContent<br/>");

        //Search keyword for each line 
        if (preg_match($background, $lineContent))
        {
            echo("Founded: $lineContent<br/>");
            echo("Previous background : $background <br/> New background : $backgroundcolor");
            //Replace the old string by the new one
            $contenuMod=str_replace($background, $backgroundcolor, $lineContent); // string to replace, new string, file
            echo ("New string: $contenuMod");
            fwrite($text,$contenuMod); 
        }
    }
    fclose($text); 
    ?>

最佳答案

str_replace 不适用于正则表达式。

preg_match 在文件中找到正则表达式 '/background-color:blue;/' 时,您应该只传递给 str_replace字符串 background-color:blue; 或使用 preg_replace

<?php 

    $fichier='texte.css';
    $backgroundcolor='background-color:yellow;';
    $background='/background-color:blue;/';

    $text=fopen($fichier,'r+') or die("File missing"); 
    $contenu=file_get_contents($fichier);
    $lines = file($fichier);
    foreach ($lines as $lineNumber => $lineContent)
    {
        echo ("$lineNumber $lineContent<br/>");
        contenuMod = preg_replace(background , backgroundcolor, $lineContent);
        fwrite($text,$contenuMod); 

    }
    fclose($text); 
    ?>

关于javascript - 用 PHP 脚本替换 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29841867/

相关文章:

php - openoffice headless 命令文档/引用

css - 带有视口(viewport)滚动内容的标题 100% 宽度

html - 使用 css 创建标签形状

javascript - 如何使闭包编译器在大型项目中通过高级优化来删除所有死代码?

javascript - Virtual DOM和Real DOM步骤简单操作

php - 显示 $_post 的结果出错,给出空

javascript - 在进行 CSS 打印时,正文部分进入页眉区域

javascript - 通过更改作用域变量值更改样式类

javascript - 将用户输入的确切日期从 Javascript 传递到 .NET

php - 在未来的 PHP 版本中,与类同名的方法将不再是构造函数; PasswordHash 有一个已弃用的构造函数