Выведите с PHP значение переменной или предварительно определенный CONSTANT из строки результата MySQL

У меня есть строка, хранящаяся в MySQL db, например:

The sky is $color and</br> the grass is GRASS_COLOR 

Когда я беру это из db и echo, я получаю вывод

 The sky is $color and the grass is GRASS_COLOR 

Хотя я уже определил константу GRASS_COLOR (т. Е. Define ('GRASS_COLOR', 'green');) ранее в скрипте и $ color (т. Е. $ Color = 'blue';). Обратите внимание, что он правильно разбивает строку с помощью html
Есть ли способ получить строку из базы данных и сделать ее вывод вместо этого после извлечения из db:

 The sky is blue and the grass is green 

EDIT: я принял отличное решение Danijel и немного изменил его, чтобы сделать его функцией, которая теперь может использоваться на любой выбранной строке MySQL (или другой)

 $color = 'blue'; define('GRASS_COLOR', 'green'); $foo = 'The sky is $color and</br> the grass is GRASS_COLOR'; // place here value from database function db_fetch_vars_constants($text) { // collect all defined variables and filter them to get only variables of string and numeric type //$values = array_filter( get_defined_vars(), function( $item ) { $values = array_filter( $GLOBALS, function( $item ) { return is_string($item) || is_numeric($item); }); // append the dollar sign to keys $keys = array_map( function( $item ) { return '$'.$item; }, array_keys( $values ) ); // create the final array by combining the arrays $keys and $values $vars = array_combine( $keys, array_values( $values ) ); // replace names of the variables with values $text = str_replace( array_keys( $vars ), array_values( $vars ), $text ); // collect all constants and replace user defined constants with values $constants = get_defined_constants( true ); $text = str_replace( array_keys( $constants['user'] ), array_values( $constants['user'] ), $text ); // we are done echo $text; } //call the function. show the result db_fetch_vars_constants($foo); 

Возможно, если вы сохраните строки DB в формате sprint_f , я не вижу другого способа:

 $color = 'blue'; define('GRASS_COLOR', 'green'); $text = 'The sky is %s and the grass is %s'; $text = sprintf( $text, $color , GRASS_COLOR ); echo $text; 

ОБНОВИТЬ

По-видимому, я был слишком поспешным с постоянством « я не вижу другого пути ». На самом деле это определенно достижимо с использованием функций get_defined_vars () и get_defined_constants () . Идея состоит в том, чтобы собрать все пользовательские переменные и константы, а затем заменить их в строке. Это может быть даже простой механизм шаблонов (если его еще нет).

 // place here value from database $text = 'The sky is $color and</br> the grass is GRASS_COLOR'; $color = 'blue'; define('GRASS_COLOR', 'green'); // collect all defined variables and filter them to get only variables of string and numeric type $values = array_filter( get_defined_vars(), function( $item ) { return is_string($item) || is_numeric($item); }); // append the dollar sign to keys $keys = array_map( function( $item ) { return '$'.$item; }, array_keys( $values ) ); // create the final array by comining the arrays $keys and $values $vars = array_combine( $keys, array_values( $values ) ); // relpace names of the variables with values $text = str_replace( array_keys( $vars ), array_values( $vars ), $text ); // collect all constants and replace user defined constants with values $constants = get_defined_constants( true ); $text = str_replace( array_keys( $constants['user'] ), array_values( $constants['user'] ), $text ); // we are done echo $text; 
 $string = 'The sky is $color and the grass is GRASS_COLOR'; $string = str_replace('$color', $color, $string); $string = str_replace('GRASS_COLOR', GRASS_COLOR, $string); 

Но это не очень хорошая идея для хранения такой строки в MySQL. Надеюсь, это только для учебных целей.

КСТАТИ. Если у вас есть еще много переменных, это будет немного сложнее. Но что-то не так со всей идеей, так что скажем, что это «глупое обходное решение». Если вы напишете, в чем проблема и почему вы храните что-то подобное в базе данных, мы можем помочь в создании лучшего решения.