iT邦幫忙

0

【如何將變數值餵入文字檔中???】

有一個文字檔 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

變數名稱和文字檔 %% 裡面是一樣的
請問怎麼做比較好呢???

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
2
wiseguy
iT邦超人 1 級 ‧ 2014-12-12 09:19:14
最佳解答
<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;
andyto202 iT邦研究生 4 級 ‧ 2014-12-12 10:39:36 檢舉

wiseguy

wiseguy 兄果然是高手
總是有辦法寫的很簡潔
^_^

wiseguy iT邦超人 1 級 ‧ 2014-12-12 20:23:49 檢舉

andyto202提到:
寫的很簡潔

哈哈 ... 可是看在傳統產業出身、以量計價的老闆眼中,我的績效是最差的 ...汗

okra iT邦研究生 3 級 ‧ 2014-12-12 21:33:28 檢舉

pretty tight偷笑

0
一級屠豬士
iT邦新手 2 級 ‧ 2014-12-10 14:33:54

sed

2
weiclin
iT邦高手 4 級 ‧ 2014-12-10 15:28:47
<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 寫到你的目的地

andyto202 iT邦研究生 4 級 ‧ 2014-12-15 00:46:39 檢舉

感謝 weiclin 兄的幫忙
但是 wiseguy 大 所寫的更為簡潔
所以最佳解答給他了
不過真的還是很感謝您
^_^

我要發表回答

立即登入回答