使用带有变量的preg_replace获取数据库记录


Using preg_replace with variable to get database record

我正在寻找一种解决方案,在该解决方案中,我可以使用preg_replace来替换正文中的某些字符串,其中一些字符串可能包含一个变量,然后该变量将调用数据库来检索替换值(或检索该值的函数)。

例如,我可能想将以下字符串替换如下-斜体中的字符串就是我正在处理的字符串:

{today} => today's date

{title} => document title

{lang:12} => from "lang" table in database where id=12

很明显,前两个很容易,但我正在为第三个而挣扎。我唯一能想到的就是替换所有没有结肠的,然后替换任何有结肠的,来触发一个函数。

您可以使用以下命令触发函数:

$s = preg_replace_callback('/'{lang:([0-9]+)'}/', function($m) {
  $id = $m[1];
  // Mysql query
  return $string_from_database;
}, $s);

更好的是,需要缓存字符串,这样就不会从数据库中多次提取:

if(preg_match_all('/'{lang:([0-9]+)'}/', $text, $m)) {
    $ids = array_unique(array_filter($m[1], function($id) {
        return (int)$id;
    }));
    $langs = array();
    if($r = mysql_query('SELECT id, txt FROM Lang WHERE id IN('.implode(', ', $ids).')')) {
        while($l = mysql_fetch_assoc($r)) $langs[$l['id']] = $l['txt'];
    }
    $text = preg_replace_callback('/'{lang:([0-9]+)'}/', function($m) use($langs) {
        $id = $m[1];
        return array_key_exists($id, $langs) ? $langs[$id] : '!!! Lang not found !!!';
    }, $text);
}