preg_replace 字符串中的常量 PHP

preg_replace constant in string PHP

我定义了常量:

defined('site_name') OR define('site_name', 'Ses');

如何用常量替换字符串中的变量?

defined('site_name') OR define('site_name', 'Ses');
$string = 'Some string with {site_name} constant';

$result = preg_replace("/{.*?}/", CONSTANT, $string);

您需要使用捕获组捕获常量(),在回调中使用它并使用 constant:

访问具有字符串名称的常量
$result = preg_replace_callback("/{(.*?)}/",
                                function($m) {
                                    return constant($m[1]);
                                }, $string);