I never used before curly braces in 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 :
1-Normal :
$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
:
$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";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.