DomingoSL
DomingoSL

Reputation: 15494

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?

Upvotes: 5

Views: 347

Answers (7)

Vasim Shaikh
Vasim Shaikh

Reputation: 4512

A Quick Solution may be this one,

<?php
function ReplaceWord($find,$replace,$srcstring)
{
retrun str_replace($find,$replace,$srcstring);
}

echo ReplaceWord("WORLD","Peter","Hello world!");

?>

Upvotes: -1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

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]]).

Upvotes: 3

Cihan Uygun
Cihan Uygun

Reputation: 2138

I think we do not need to think complex things about this need. If we try to keep it simple, you may use sprintf function for php to format text can you try the code below;

<?PHP
    $format = "Hello %s, nice to meet %s";
    $jsonData = "{\"var1\": \"World\", \"var2\": \"You\" }";
    $data = json_decode($jsonData);
    $result = sprintf($format,$data->var1,$data->var2);
    echo $result;
?>

Working example is here https://ideone.com/AGNZen

Upvotes: 1

Naumov
Naumov

Reputation: 1167

<?php 
    $data = array("var1" => "World", "var2" => "You");
    echo "Hello {$data['var1']}, nice to meet {$data['var2']}";
?>

refactoring...

Upvotes: 1

Makwana Ketan
Makwana Ketan

Reputation: 1388

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;
?>

Upvotes: 2

Anand Singh
Anand Singh

Reputation: 2363

You can use preg_replace_callback for this.

Code Example :

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

    function replacementFunction($groups) {
       //code login here
       return "value"; 
    }

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

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
}

Upvotes: 3

Related Questions