我以前从未在 php 中使用过大括号
但是我正在更新现有网站...
在数据库中我有诸如
之类的信息YOUR NAME {CH_NAME} {URL_NAME}
我想检索信息并以适当的方式显示 我想将 CH_NAME 变量影响为一个与 URL_NAME 相同的值,并在最终显示完整信息,例如:
1-正常:
$beforeStr="YOUR NAME {CH_NAME} {URL_NAME}";
$CH_NAME="John";
$URL_NAME="http://xxxx";
echo $beforeStr ; //would like to show : YOUR NAME John http://xxxx
问候
只有你必须使用
str_replace
:
$beforeStr="YOUR NAME {CH_NAME} {URL_NAME}";
$CH_NAME="John";
$URL_NAME="http://xxxx";
$OTHER = "OTHER";
$beforeStr = str_replace(
array('{CH_NAME}','{URL_NAME}','{OTHER}'),
array($CH_NAME,$URL_NAME,$OTHER),
$beforeStr);
echo $beforeStr ;
另一种方式是:
$beforeStr = "YOUR NAME {CH_NAME} {URL_NAME} - {OTHER} ";
$variables = array(
'CH_NAME'=>'John',
'URL_NAME'=>'http://xxxx',
'OTHER'=>'other'
);
//if var exist then replace
$response = preg_replace_callback('/{(.+?)}/ix',function($match)use($variables){
return !empty($variables[$match[1]]) ? $variables[$match[1]] : $match[0];
},$beforeStr);
echo $response;
如果你真的想使用花括号,试试这个。所有替换都将自动完成,只需根据匹配的变量名称即可。
$CH_NAME = "John";
$URL_NAME = "http://xxxx";
$beforeStr = "YOUR NAME {CH_NAME} {URL_NAME}";
preg_match_all('/{(\w+)}/', $beforeStr, $matches);
$afterStr = $beforeStr;
foreach ($matches[0] as $index => $var_name) {
if (isset(${$matches[1][$index]})) {
$afterStr = str_replace($var_name, ${$matches[1][$index]}, $afterStr);
}
}
echo $afterStr;
使用字符串插值。您需要使用双引号分隔字符串
"
。然后只需在大括号前加上美元符号即可:
echo "Hello ${NAME}";
大括号实际上对你没有任何作用,因为以下内容也有效:
echo "Hello $NAME";
这里有一个简单的函数可以帮助您。这个取自 Yii::t() 函数。
function replace_placeholder($message, $params = [])
{
$placeholders = [];
foreach ((array) $params as $name => $value) {
$placeholders['{' . $name . '}'] = $value;
}
return ($placeholders === []) ? $message : strtr($message, $placeholders);
}
以下是该功能的使用方法,
$beforeStr="YOUR NAME {CH_NAME} {URL_NAME}";
$values = ['CH_NAME'=>"John",'URL_NAME'=>"http://xxxx"];
echo replace_placeholder($beforeStr,$values);
完整示例在这里
<?php
function replace_placeholder($message, $params = [])
{
$placeholders = [];
foreach ((array) $params as $name => $value) {
$placeholders['{' . $name . '}'] = $value;
}
return ($placeholders === []) ? $message : strtr($message, $placeholders);
}
$beforeStr="YOUR NAME {CH_NAME} {URL_NAME}";
$values = ['CH_NAME'=>"John",'URL_NAME'=>"http://xxxx"];
echo replace_placeholder($beforeStr,$values);