PHP 用数组元素值替换大括号之间的字符串
PHP replace string between curly brackets with array element value
我读入了大量内容,其中包含许多字符串,例如 {{some_text}}
,我想要做的是找到所有这些事件并将它们替换为数组中的另一个值例如 $text["some_text"]
.
我试过使用 preg_replace 但不确定如何将找到的文本放在括号之间并将其用于替换值。
$body = "This is a body of {{some_text}} text from a book.";
$text["some_text"] = "really cool";
$parsedBody = preg_replace("\[{].*[}]/U", $text[""], $body);
如您所见,我正在尝试从字符串中获取 some_text
文本并使用它来调用数组中的元素,这个示例非常基础,因为有 $body
value大得多,$text
也有几百个元素。
您可以使用 preg_replace_callback
并使用捕获组 ([^}]+)
在数组 $text
:
中查找索引
$repl = preg_replace_callback('/{{([^}]+)}}/', function ($m) use ($text) {
return $text[$m[1]]; }, $body);
//=> This is a body of really cool text from a book.
use ($text)
语句将$text
的引用传递给匿名的function
。
只是为了好玩,按原样使用您的数组:
$result = str_replace(array_map(function($v){return '{{'.$v.'}}';}, array_keys($text)),
$text, $body);
或者,如果您的数组类似于 $text['{{some_text}}']
,那么只需:
$result = str_replace(array_keys($text), $text, $body);
如何反过来做 - 而不是查找所有 {{...}}
占位符并查找它们的值,遍历所有值并替换匹配的占位符,如下所示:
foreach ($text as $key => $value) {
$placeholder = sprintf('{{%s}}', $key);
$body = str_replace($placeholder, $value, $body);
}
你甚至可以把它包装成一个函数:
function populatePlaceholders($body, array $vars)
{
foreach ($vars as $key => $value) {
$placeholder = sprintf('{{%s}}', $key);
$body = str_replace($placeholder, $value, $body);
}
return $body;
}
我读入了大量内容,其中包含许多字符串,例如 {{some_text}}
,我想要做的是找到所有这些事件并将它们替换为数组中的另一个值例如 $text["some_text"]
.
我试过使用 preg_replace 但不确定如何将找到的文本放在括号之间并将其用于替换值。
$body = "This is a body of {{some_text}} text from a book.";
$text["some_text"] = "really cool";
$parsedBody = preg_replace("\[{].*[}]/U", $text[""], $body);
如您所见,我正在尝试从字符串中获取 some_text
文本并使用它来调用数组中的元素,这个示例非常基础,因为有 $body
value大得多,$text
也有几百个元素。
您可以使用 preg_replace_callback
并使用捕获组 ([^}]+)
在数组 $text
:
$repl = preg_replace_callback('/{{([^}]+)}}/', function ($m) use ($text) {
return $text[$m[1]]; }, $body);
//=> This is a body of really cool text from a book.
use ($text)
语句将$text
的引用传递给匿名的function
。
只是为了好玩,按原样使用您的数组:
$result = str_replace(array_map(function($v){return '{{'.$v.'}}';}, array_keys($text)),
$text, $body);
或者,如果您的数组类似于 $text['{{some_text}}']
,那么只需:
$result = str_replace(array_keys($text), $text, $body);
如何反过来做 - 而不是查找所有 {{...}}
占位符并查找它们的值,遍历所有值并替换匹配的占位符,如下所示:
foreach ($text as $key => $value) {
$placeholder = sprintf('{{%s}}', $key);
$body = str_replace($placeholder, $value, $body);
}
你甚至可以把它包装成一个函数:
function populatePlaceholders($body, array $vars)
{
foreach ($vars as $key => $value) {
$placeholder = sprintf('{{%s}}', $key);
$body = str_replace($placeholder, $value, $body);
}
return $body;
}