tags:

views:

54

answers:

2

Sorry, I am confused to create a correct title. This is my problem, I have a TXT file:

{{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...

A: 
$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 ;)

nikic
Note that the version using regex needs PHP >= 5.3
NullUserException
+2  A: 

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.

NullUserException
PHP is a templating engine, but if you don't trust the template writer, it may very well be necessary to define a simpler template language inside PHP.
tdammers
And PHP for templateing isn't really nice to write nor to look at.
nikic
@nick Well, I think it's just fine, but to each his own.
NullUserException
well, I am thinking just like @NullUserException, php itself is templating engine and I am developing my own simple cms or framework for my team. I didnt use any php templating like smarty instead php tags inside html page. But I'm also thinking to create a quick replacement system in the html using own tag like that.
Vina
@Vina You should look really into [MVC](http://oreilly.com/php/archive/mvc-intro.html) and write Views in pure PHP. There is also a number of open source MVC frameworks available: [CakePHP](http://cakephp.org/), [CodeIgniter](http://codeigniter.com/), [Symfony](http://www.symfony-project.org/) just to name a few.
NullUserException