用CSV数据替换模板中的字符串

时间:2018-07-19 15:49:10

标签: php string replace

我使用kubectl patch svc istio-service -p '{"spec":{"type":"NodePort"}}' 。我正在读取以下csv文件:

PHP 5.5.9-1ubuntu4.22

我想用csv值替换以下模板:

模板:

Product;Category;Manufacturer;Price;hasWlan Product 8;Category 1;Manifacturer - 9;3;f Product 7;Category 8;Manifacturer - 1;5;t Product 9;Category 8;Manifacturer - 1;10;t Product 9;Category 2;Manifacturer - 7;7;f Product 5;Category 9;Manifacturer - 2;7;t Product 5;Category 3;Manifacturer - 7;10;t Product 6;Category 10;Manifacturer - 4;1;t Product 5;Category 7;Manifacturer - 2;1;t Product 5;Category 1;Manifacturer - 6;6;t

想要的结果:

@attr(Product) has the @attr(Category) from the @attr(Manufacturer).

我尝试了以下php脚本:

Product 8 has the Category 1 from the Manufacturer - 9.
Product 7 has the Category 8 from the Manufacturer - 1.

etc.

但是,我目前收到以下输出:

<?php
class StringTemplate
{
    public function process($text, $singleVariable, $data) {

        // 1. Replace Variables
        $pattern = '@attr(' . $singleVariable . ')'; 
        $text = str_replace($pattern, $data, $text);

        // return final result
        return $text;
    }

}

/*******************/
/***EXAMPLE USAGE***/
/*******************/

// 1. Read in csv
$csvFile = '/home/ubuntu/workspace/src/SampleText.csv';

echo "\n";
$StringTemplate = new StringTemplate();
$template = "@attr(Product) has the @attr(Category) from the @attr(Manufacturer). ";

$row = 0;
$vars = array();
if (($handle = fopen($csvFile, "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 10000, ";")) !== FALSE) {
    $num = count($data);
    for ($c=0; $c < $num; $c++) {
        echo $StringTemplate->process($template, $vars, $data[$c]);
    }
    if($row == 0) {
        $vars = $data;
        echo print_r($vars) . "\n";
    }
    echo "####################### \n";
    $row++;
  }
  fclose($handle);
}

如您所见,脚本中的数据没有被替换。

有人建议为什么会这样吗?

感谢您的答复!

1 个答案:

答案 0 :(得分:1)

由于您的$singleVariable 不是单个变量(重命名,不要让自己和其他人感到困惑),因此您应该从中创建一系列替换项。因此,我认为您应该替换

$pattern = '@attr(' . $singleVariable . ')';

具有:

$pattern = [];
foreach ($singleVariable as $variable) {
    $pattern[] = '@attr(' . $variable . ')'; 
}

该函数的其余代码保持不变。由于str_replace可以与数组一起使用,所以一切都应该起作用。 另外,您应该将while循环修复为此:

while (($data = fgetcsv($handle, 10000, ";")) !== FALSE) {
    // here you get headers, there's no need to increment `$row` any more than here
    if ($row == 0) {
        $vars = $data;
        $row++;
        //echo print_r($vars) . "\n";
    }
    // here you replace - array of `$vars` to array of `$data`
    echo $StringTemplate->process($template, $vars, $data);
}