PHP replace dynamic content based on position in string

自闭症网瘾萝莉.ら 提交于 2019-12-13 10:18:48

问题


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?


回答1:


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.




回答2:


$body = "This question is a {{x}} of {{y}} within SO.";

$text = ['possible duplicate', '@21100035'];

echo preg_replace_callback('~{{[^{}]++}}~', function($m) use ($text, &$count) {
    return $text[(int)$count++] ?? $m[0];
}, $body, -1, $count);

// Output
// This question is a possible duplicate of @21100035 from SO.

Live demo




回答3:


<?php

$body = "This question is a {{x}} of {{y}} within SO.";

$searches = ['{{x}}', '{{y}}'];
$replaces = ['possible duplicate', '@21100035'];

echo str_replace($searches, $replaces, $body);

// Output
// This question is a possible duplicate of @21100035 from SO.

EDIT: IF YOU DON'T KNOW X & Y THEN YOU CAN TRY THIS

<?php

$body = "This question is a {{x}} of {{y}} within SO.";

preg_match_all('/\{\{(.*?)\}\}/', $body, $matches);

$searches = $matches[0];
$replaces = ['possible duplicate', '@21100035'];

echo str_replace($searches, $replaces, $body);

// Output
// This question is a possible duplicate of @21100035 from SO.


来源:https://stackoverflow.com/questions/47378516/php-replace-dynamic-content-based-on-position-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!