Sorry, I am confused to create a correct title. This is my problem, I have a TXT file:
开发者_如何学Go{{title}}<br />{{content}}
And this is the PHP file: I load file.txt and replace tags {{variable}} with value from $data['variable']
$data = array ( 'title' => 'Hello', 'content' => 'WORLD!!');
$file = file_get_contents("file.txt");
$key = array_keys($data);
$value = array_values($data);
$file = str_replace($key, $value, $file);
echo $file;
nothing change from file.txt
I have 2 way to solve this by assign array's key in this format
'{{variable}}' => 'value'
or write
str_replace(array('{{','}}'),'',$file)
before
echo $file;
Is there are another way?
thx before...
Yes.
function bracelize($str) {
return '{' . $str . '}';
}
$search = array_map('bracelize', $key);
Then just use the $search
array.
If you are using PHP >= 5.3 you can use an anonymous function if you don't want to pollute the namespace:
$search = array_map(function($str){ return '{'. $str .'}';}, $key);
That being said, if you are planning to use this as an HTML templating system, please don't. PHP itself is a templating engine; why add more overhead? Read this question.
$data = array ( 'title' => 'Hello', 'content' => 'WORLD!!');
$file = file_get_contents("file.txt");
foreach ($data as $key => $value) {
$file = str_replace('{{' . $key . '}}', $value);
}
echo $file;
though probably this will be slower.
Another version using regex:
$file = preg_replace_callback('#\{\{([A-Za-z0-9]+)\}\}#', function($match) use($data) {
if (isset($data[$match[1]])) {
return $data[$match[1]];
}
}, $file);
Another (and my preferred version) is to replace all #{{([A-Za-z0-9)}}#
in the file with <?php echo isset($data['$1']) ? $data['$1'] : null; ?>
, cache the resulting PHP Code and then execute providing the $data
array ;)
精彩评论