Mysql
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> Mysql

Xuất với PHP giá trị của một biến hoặc một CONSTANT được xác định trước từ chuỗi kết quả MySQL

Có thể nếu bạn lưu các chuỗi DB trong sprint_f định dạng, tôi không thấy cách khác:

$color = 'blue';
define('GRASS_COLOR', 'green');

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

echo $text;

CẬP NHẬT

Rõ ràng là tôi đã hơi quá vội vàng với việc xác định ' tôi không thấy cách nào khác '. Trên thực tế, điều này chắc chắn có thể đạt được khi sử dụng get_defined_vars () get_defined_constants () chức năng. Ý tưởng là thu thập tất cả các biến và hằng số do người dùng xác định, sau đó thay thế các biến và hằng số đó trong một chuỗi. Đây thậm chí có thể là một công cụ mẫu đơn giản (nếu chưa tồn tại).

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


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. thiết lập virtualenv để phát triển django trên windows,

  2. Công ty lưu trữ web của tôi cho biết có điều gì đó sai với mã PHP

  3. Đặt giá trị AUTOINCREMENT trong bảng django

  4. Làm thế nào để thiết lập Hibernate để đọc / ghi vào các nguồn dữ liệu khác nhau?

  5. Nhận điểm đa giác mysql