[英]Replace sub string using array key in php
Replace string using array使用数组替换字符串
$array = ['name' => 'John', 'other' => 'I am working'];
$content = "Hi {name}, {other}";
//$expected = "Hi John, I am working";
I need help to create a function that will search for an array key name in a string and replace any instance the key name (with the curl brackets) with the array value and return the expected我需要帮助来创建一个函数,该函数将在字符串中搜索数组键名,并用数组值替换键名(带有花括号)的任何实例并返回预期
Simply create a function like this简单地创建一个这样的函数
function replace($content, $array)
{
foreach ($array as $key => $val)
{
$content = str_replace('{'.$key.'}', $val, $content);
}
return $content;
}
And call using并调用使用
This will work perfect for you这将非常适合你
Function:功能:
function replace($content, $array)
{
return str_replace(
array_map(function ($v) {
return '{' . $v . '}';
}, array_keys($array)),
array_values($array),
$content
);
}
Use:用:
$array = ['name' => 'John', 'other' => 'I am working'];
$content = "Hi {name}, {other}";
echo replace($content, $array);
// ==> Hi John, I am working
It needs PHP 5.3 or major.它需要 PHP 5.3 或主要版本。
This is a very simple approach using what you've provided:这是使用您提供的内容的一种非常简单的方法:
foreach ($array as $key => $val){
$content = str_replace('{'.$key.'}', $val, $content);
}
I am unsure if the format "{$key}"
would work, as the curly brackets would likely need escaping, so I chose to use simple string concatenation.我不确定格式
"{$key}"
是否有效,因为大括号可能需要转义,所以我选择使用简单的字符串连接。
Why don't you simply loop through your array and replace everything?为什么不简单地遍历数组并替换所有内容?
$array = ['name' => 'John', 'other' => 'I am working'];
$content = "Hi {name}, {other}";
foreach ($array as $key => $replacement) {
$content = str_replace('{' . $key . '}', $replacement, $content);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.