Search code examples
phpregexpreg-replace-callback

PHP replace dynamic content based on position in string


What I would like :

The values to replace are between {{ }}.

Input : "this is letter {{ A }} and {{ B }}"

but it can change : "this is letter {{ AAAA }} and {{ BBB }}"

with array ("C", "D")

Output : "this is letter C and D


I don't know in advance the string between {{ }} and I would like to extract those strings and replace them with another value :

What I tried :

$body = "This is a body of {{awesome}} text {{blabla}} from a book.";


//Only work if we know the keys (awesome, blabla,...)
$text["awesome"] = "really cool"; 
$text["blabla"] = "";
echo str_replace(array_map(function($v){return '{{'.$v.'}}';},    array_keys($text)), $text, $body);

Result :

This is a body of really cool text from a book.

Problem :

I cannot find something similar to this already asked (there is only when we know before the old content between brackets, but mines are "dynamic"), so the solution with array_map or preg_replace_callback doesn't work.

Any idea on how I can do this?


Solution

  • I think this is what you are after:

    $body = "This is a body of {{awesome}} text {{blabla}} from a book.";
    $count = 0;
    $terms[] = '1';
    $terms[] = '2';
    echo preg_replace_callback('/\{{2}(.*?)\}{2}/',function($match) use (&$count, $terms) {
        $return = !empty($terms[$count]) ? $terms[$count] : 'Default value for unknown position';
        $count++;
        return $return;
    }, $body);
    

    Demo: https://3v4l.org/Ktaod

    This will find each {{}} pairing and replace the value with a value from an array based on the position it was found in the string.

    The regex \{{2}(.*?)\}{2} is just looking for 2 {s, anything in between, and then 2 }s.