使用preg_replace with variable来获取数据库记录

时间:2012-07-24 13:58:57

标签: php preg-replace

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

例如,我可能想要替换以下字符串,如下所示 - 斜体中的字符串是我正在努力的字符串:

{today} => today's date

{title} => document title

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

显然,前两个很容易,但我正在努力争取第三个。我唯一能想到的就是替换所有没有冒号的东西,然后替换任何有冒号的东西来触发一个函数。

1 个答案:

答案 0 :(得分:4)

您可以使用以下方法触发功能:

$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);
}