PHP – заменить строку на переменную с именем like string

поэтому строка выглядит так:

"bla bla bla {VARIABLE} bla bla" 

когда я использую эту строку где-то в функции, которую я хочу заменить {VARIABLE} переменной $ (или любыми другими строками верхнего регистра, завернутыми в {} charcters). переменная $ (и любые другие переменные) будет определена внутри этой функции

Я могу сделать это?

 $TEST = 'one'; $THING = 'two'; $str = "this is {TEST} a {THING} to test"; $result = preg_replace('/\{([AZ]+)\}/e', "$$1", $str); 

Используйте регулярное выражение, чтобы найти все подстановки, затем перебрать результат и заменить их. Обязательно укажите только переменные, которые вы хотите просмотреть.

 // white list of variables $allowed_variables = array("test", "variable", "not_POST", "not_GET",); preg_match("#(\{([AZ]+?)\}#", $text, $matches); // not sure the result is in [1], do a var_dump while($matches[1] as $variable) { $variable = strtolower($variable); // only allow white listed variables if(!in_array($variable, $allowed_variables)) continue; $text = str_replace("{".$match."}", $$match, $text); } 

Опираясь на некоторые другие ответы (особенно Билл Карвин и букет) …

  class CurlyVariables { private static $_matchable = array(); private static $_caseInsensitive = true; private static function var_match($matches) { $match = $matches[1]; if (self::$_caseInsensitive) { $match = strtolower($match); } if (isset(self::$_matchable[$match]) && !is_array(self::$_matchable[$match])) { return self::$_matchable[$match]; } return ''; } public static function Replace($needles, $haystack, $caseInsensitive = true) { if (is_array($needles)) { self::$_matchable = $needles; } if ($caseInsensitive) { self::$_caseInsensitive = true; self::$_matchable = array_change_key_case(self::$_matchable); } else { self::$_caseInsensitive = false; } $out = preg_replace_callback("/{(\w+)}/", array(__CLASS__, 'var_match'), $haystack); self::$_matchable = array(); return $out; } } 

Пример:

 echo CurlyVariables::Replace(array('this' => 'joe', 'that' => 'home'), '{This} goes {that}', true); 

Использование $$vars и $GLOBALS представляет угрозу безопасности. Пользователь должен иметь возможность явно определять список допустимых тэгов.

Ниже – простейшее однофункциональное общее решение, которое я мог бы разработать. Я решил использовать двойные фигурные скобки как разделители тегов, но вы можете легко их модифицировать.

 /** * replace_tags replaces tags in the source string with data from the vars map. * The tags are identified by being wrapped in '{{' and '}}' ie '{{tag}}'. * If a tag value is not present in the tags map, it is replaced with an empty * string * @param string $string A string containing 1 or more tags wrapped in '{{}}' * @param array $tags A map of key-value pairs used to replace tags * @param force_lower if true, converts matching tags in string via strtolower() * before checking the tags map. * @return string The resulting string with all tags replaced. */ function replace_tags($string, $tags, $force_lower = false) { return preg_replace_callback('/\\{\\{([^{}]+)\}\\}/', function($matches) use ($force_lower, $tags) { $key = $force_lower ? strtolower($matches[1]) : $matches[1]; return array_key_exists($key, $tags) ? $tags[$key] : ''; } , $string); } 

[edit] Добавлен параметр force_lower

[edit] Добавлен параметр force_lower var для use – благодаря тому, кто начал отклоненное редактирование.

Это будет работать ….

 $FOO = 'Salt'; $BAR = 'Peppa'; $string = '{FOO} and {BAR}'; echo preg_replace( '/\{([AZ]+)\}/e', "$$1", $string ); 

но это просто кажется ужасной идеей.

Следующее – это другое решение, но я согласен с другими людьми, которые сомневаются в том, что для вас это разумно.

 <?php $string = "bla bla bla {VARIABLE} bla bla"; $VARIABLE = "foo"; function var_repl($matches) { return $GLOBALS[$matches[1]]; } echo preg_replace_callback("/{(\w+)}/", "var_repl", $string); 

Я рад, что нашел решение Билла Крисвелла, но также возможно заменить такие переменные:

string tmp = "{myClass.myVar}";

Где PHP-код будет что-то вроде:

 class myClass { public static $myVar = "some value"; } 
 $data_bas = 'I am a {tag} {tag} {club} {anothertag} fan.'; // Tests $vars = array( '{club}' => 'Barcelona', '{tag}' => 'sometext', '{anothertag}' => 'someothertext' ); echo strtr($data_bas, $vars);