Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replace in PHP with return function

In javascript you can define a return function when you do string replacements:

function miniTemplate(text, data) { 
    return text.replace(/\{\{(.+?)\}\}/g, function(a, b) {
        return typeof data[b] !== 'undefined' ? data[b] : '';
    });
}

This few lines of code allow me to create a very neat template system. The regular expression matches all the "{{something}}" strings inside the text variable and the return function matches if something is inside the object data, and if it is, it replaces it.

So,

text = "Hello {{var1}}, nice to meet {{var2}}";
data = { var1: "World", var2: "You" }
//result => "Hello World, nice to meet You"

Im trying to replicate this functionality is PHP, but the only solution that comes to my mind is using 2 cicles, one that parse each element of data array and the second one inside the first that looks for the string inside Text.

Is there a cleaner way in php?

like image 682
DomingoSL Avatar asked Jan 27 '16 11:01

DomingoSL


3 Answers

You can use a preg_replace_callback just the same way as in JavaScript like this (pass the $data array to the preg_replace_callback using the uses keyword):

function miniTemplate($text, $data) { 
     return preg_replace_callback('~\{\{(.*?)}}~', function ($m) use ($data) {
         return isset($data[$m[1]]) ? $data[$m[1]] : $m[0]; 
     }, $text);
}
$text = "Hello {{var1}}, nice to meet {{var2}}";
$data = array("var1" => "World", "var2"=> "You");
echo miniTemplate($text, $data); // => Hello World, nice to meet You at {{var3}}

See IDEONE demo

If a value is missing in $data, the template string will be returned as we first check if it is present with isset($data[$m[1]]).

like image 121
Wiktor Stribiżew Avatar answered Oct 20 '22 07:10

Wiktor Stribiżew


Yes, in PHP, there is a function preg_replace_callback() that you can pass a function to to handle the replacement:

$result = preg_replace_callback('/\{\{(.+?)\}\}/', 'do_replacement', $subject);

function do_replacement($groups) {
    // $groups[0] holds the entire regex match
    // $groups[1] holds the match for capturing group 1
    return ''; // actual program logic here
}
like image 3
Tim Pietzcker Avatar answered Oct 20 '22 06:10

Tim Pietzcker


Try this code. it will definetely help you.

<?php
$text = "Hello {{var1}}, nice to meet {{var2}}";
$data = array("var1"=>"World","var2"=>"You");
foreach($data as $key => $value){
   $text = str_replace('{{'.$key.'}}', $value, $text);
}
echo $text;
?>
like image 2
Makwana Ketan Avatar answered Oct 20 '22 07:10

Makwana Ketan