PHP根据字符串

时间:2017-11-19 15:25:25

标签: php regex preg-replace-callback

我想要的是什么:

要替换的值介于{{ }}之间。

输入: "这是字母{{A}}和{{B}}"

但它可以改变:"这是字母{{AAAA}}和{{BBB}}"

  

with array(" C"," D")

输出:"这是字母C和D

我事先并不知道{{ }}之间的字符串,我想提取这些字符串并将其替换为其他值:

我尝试了什么:

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

结果:

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

问题:

我找不到类似于此问题的东西(只有当我们知道括号之间的旧内容之前,但是地雷是"动态"),所以 array_map 或 preg_replace_callback 无效。

我对如何做到这一点有任何想法?

3 个答案:

答案 0 :(得分:1)

$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

答案 1 :(得分:1)

我认为这就是你所追求的目标:

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

演示:https://3v4l.org/Ktaod

这将找到每个{{}}配对,并根据在字符串中找到的位置将值替换为数组中的值。

正则表达式\{{2}(.*?)\}{2}只是寻找2 { s,介于两者之间,然后是2 } s。

答案 2 :(得分:0)

\[([0-9a-z]+\.\.[0-9a-z]+)\] * : *([0-9])+;

修改: 如果你不知道X&你然后可以尝试

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