繁体   English   中英

用PHP数组中的值替换子字符串

[英]Replacing a substring with values from an array in PHP

我正在尝试使用数组编写JSON文件。 最初,该文件用于在服务器上创建colorbook.js文件,然后手动查找并替换以将所有值添加到其中。 这是代码:

<?php
$colorsperpage = 48; // format is 6 columns by 8 rows
$letters = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K');
$hexValues = array('ECECEC', 'D9D9D9', 'C7C7C7', 'B4B4B4', 'A2A2A2');

$txt = "var color = {\r\n";

for ($i = 0 ; $i < count($letters) ; $i++){
    $pagenum = $i + 1;
    for ( $j = 1; $j <= $colorsperpage; $j++ ){
        if ($j < 10){
            if ($j == $colorsperpage){
                $txt .= "\t\"" . $letters[$i] . $pagenum . "-" . "0" . $j . "\"  :  \"rgba(255,255,255,1)\"\r\n";
            } else {
                $txt .= "\t\"" . $letters[$i] . $pagenum . "-" . "0" . $j . "\"  :  \"rgba(255,255,255,1)\",\r\n";
            }
        } else {
            if ($j == $colorsperpage){
                $txt .= "\t\"" . $letters[$i] . $pagenum . "-" . $j . "\"  :  \"rgba(255,255,255,1)\"\r\n";
            } else {
                $txt .= "\t\"" . $letters[$i] . $pagenum . "-" . $j . "\"  :  \"rgba(255,255,255,1)\",\r\n";
            }

        }
    }
};


$txt .= "};";

foreach ($hexValues as $hex){
    $txt = preg_replace('/rgba(255,255,255,1)/', $hex, $txt, 1);
}
$jsonFile = fopen('colorbook.js', 'w') or die('Unable to open file!');
fwrite($jsonFile, $txt);
fclose($jsonFile);
?>

原始脚本确实正确写入了文件(如果删除了foreach循环)。 我假设运行preg_replace将遍历该字符串,并且一次替换一个十六进制值。 请注意,原始数组为528个项目; 我将其缩短以便在此处发布。 每个RGBA条目一个。 有人可以让我知道我在做什么错吗? 谢谢。

不要手动创建JSON。 循环构建数组,并在最终结果上使用json_encode() 您可以在循环期间从数组中获取十六进制代码,而不是随后进行数百次字符串替换。

要格式化数组键,可以使用sprintf()连接所有片段,并在$j前加零。

<?php
$result = [];
$color_index = 0;
foreach ($letters as $i => $letter) {
    $pagenum = $i + 1;
    for ($j = 1; $j <= $colorsperpage; $j++) {
        $key = sprintf("%s%d-%02d", $letter, $pagenum, $j);
        $colorcode = $hexValues[$color_index++];
        $result[$key] = $colorcode;
    }
}
file_put_contents("colorbook.js", "var color = " . json_encode($result));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM