我正在我的网站中生成 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/