我想找到下面$text
括号中的所有值,并使用$data
数组中的正确值替换:
1) $text = "My name is {NAME} {SURNAME} and I have {NUMBER} dogs";
2) $text = "My name is {NAME}. I have {COLOR} car.";
问题是我不知道有多少(示例显示3或2,但它可以是4或6或更多)。
$data["name"] = "John";
$data["surname"] = "Smith";
$data["number"] = 2;
$data["color"] = red;
依旧......
这样做最简单的方法是什么?我正在使用str_replace()
,但对我来说困难的是在括号中找到值。
function findAndReplace($text, $data) {
return $newText;
}
答案 0 :(得分:4)
preg_replace_callback()
非常适合这项工作。
尝试了解此代码的作用,而不是盲目地复制粘贴它:)
(请注意,您的密钥总是小写的( {NAME} vs $ data [" name"] 实施例)。子>
function findAndReplace($text, array $data)
{
return preg_replace_callback('/\\{(\w++)\\}/', function ($match) use ($data) {
$key = mb_strtolower($match[1]);
if (isset($data[$key])) {
return $data[$key];
}
}, $text);
}
<强>用法:强>
$text = "My name is {NAME} {SURNAME} and I have {NUMBER} dogs";
$data["name"] = "John";
$data["surname"] = "Smith";
$data["number"] = 2;
$data["color"] = "red";
var_dump(
findAndReplace($text, $data)
);
<强>输出:强>
string(39)&#34;我的名字是John Smith,我有2只狗&#34;
答案 1 :(得分:2)
<?php
$text = "My name is {name} {surname} and I have {number} dogs";
$data["name"] = "John";
$data["surname"] = "Smith";
$data["number"] = 2;
$data["color"] = "red";
foreach($data as $key=>$value){
$key="{".$key."}";
$text=str_replace($key,$value,$text);
}
echo $text;
?>
答案 2 :(得分:1)
如果您的数组键可以与您需要更改的模式具有相同的名称,则可以执行以下操作:
$data["{NAME}"] = "John";
$data["{SURNAME}"] = "Smith";
$data["{NUMBER}"] = 2;
$data["{COLOR}"] = red;
$result = str_replace(array_keys($data), array_values($data), $text);
否则你可以在字符串中小写你的模式并删除括号:
$result = str_replace(array_keys($data), array_values($data), $text);
答案 3 :(得分:0)
这是使用最简单的str_replace()
函数和foreach循环的一种方法。
function findAndReplace($text, $data)
{
foreach ( $data as $name => $val) {
$t = sprintf('{%s}',strtoupper($name));
$text = str_replace($t, $val, $text);
}
return $text;
}
$text = "My name is {NAME} {SURNAME} and I have {NUMBER} dogs";
$data["name"] = "John";
$data["surname"] = "Smith";
$data["number"] = 2;
$data["color"] = "red";
$text = "My name is {NAME} {SURNAME} and I have {NUMBER} dogs";
echo findAndReplace($text, $data) . PHP_EOL;
$text = "My name is {NAME}. I have {COLOR} car.";
echo findAndReplace($text, $data);
结果:
My name is John Smith and I have 2 dogs
My name is John. I have red car.