简体   繁体   English

PHP花括号替换值

[英]php curly braces replace values

I never used before curly braces in php 我从未在php中使用花括号

However i'm updating an existant website... 但是我正在更新一个现有的网站...

In database i have information such as in 在数据库中,我有诸如

YOUR NAME {CH_NAME} {URL_NAME}

I would like to retrieve the information and show it in appropriate I want to affect the CH_NAME Variable to a value & same to URL_NAME and in final show full infrmation such : 我想检索信息并将其显示在适当的位置,以使CH_NAME变量的值与URL_NAME相同,并最终显示完整的信息,例如:

1-Normal : 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

Regards 问候

Only you have to use str_replace : 只有您必须使用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 ;

other way is: 另一种方法是:

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

If you really want to use curly braces, try this. 如果您真的想使用花括号,请尝试此操作。 All replaces will be done automatically, just from matched variable names. 所有替换将自动完成,仅从匹配的变量名称开始。

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

Use string interpolation. 使用字符串插值。 You need to use double-quote delimited strings " . Then just prefix your braces with a dollar sign: 您需要使用双引号定界字符串" 。然后在括号中加一个美元符号:

echo "Hello ${NAME}";

The braces don't really do anything for you though, as the following works too: 括号实际上并没有为您做任何事情,因为以下方法也可以:

echo "Hello $NAME";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM