phpcurly-braces

php curly braces replace values


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


Solution

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