有一個文字檔 abc.txt
內容如下
conf
port ethernet %left2%
encapsulation dot1q
dot1q pvc %left3% profile to-dot1p
description %sub%
qos policy policing %qospolicy%
bind bypss
end
conf
port ethernet %right2%
encapsulation dot1q
dot1q pvc %right3% profile from/to-dot1p
description %sub%
bind bypss
end
conf
xc-group default
xc %left2% vlan-id %left3% to %right2% vlan-id %right3%
end
我有6個變數
$left2 = '1/1';
$left3 = '111';
$sub = 'abc';
$qospolicy = 'bbb';
$right2 = '2/2';
$right3 = '222';
想要分別把這6個值餵給文字檔
變成
conf
port ethernet 1/1
encapsulation dot1q
dot1q pvc 111 profile to-dot1p
description aaa
qos policy policing bbb
bind bypss
end
conf
port ethernet 2/2
encapsulation dot1q
dot1q pvc 222 profile from/to-dot1p
description aaa
bind bypss
end
conf
xc-group default
xc 1/1 vlan-id 111 to 2/2 vlan-id 222
end
變數名稱和文字檔 %% 裡面是一樣的
請問怎麼做比較好呢???
<pre class="c" name="code"><?php
// 讀取你的文字檔
$template = file_get_contents("abc.txt");
$left2 = '1/1';
$left3 = '111';
$sub = 'abc';
$qospolicy = 'bbb';
$right2 = '2/2';
$right3 = '222';
$output = preg_replace_callback('/%(.*?)%/', function ($match){return $GLOBALS[$match[1]];}, $template);
echo $output;
<pre class="c" name="code">
<?php
// 讀取你的文字檔
$template = file_get_contents("template.txt");
$left2 = '1/1';
$left3 = '111';
$sub = 'abc';
$qospolicy = 'bbb';
$right2 = '2/2';
$right3 = '222';
$found = preg_match_all("/%(.+?)%/", $template, $matches);
$output = "";
if ($found) {
$replace = array();
foreach ($matches[1] as $varName) {
$value = isset($$varName) ? $$varName : "undefined";
array_push($replace, $value);
}
$output = str_replace($matches[0], $replace, $template);
}
echo "result:\n$output\n";
自己把 $output 寫到你的目的地