3

I am looking for a solution where I can use preg_replace to replace certain strings in a body of text where some of the strings may contain a variable which will then call upon a database to retrieve the replacement value (or a function which retrieves that value).

For example, I may want to replace the following strings as follows - the one in italics is the one I am struggling with:

{today} => today's date

{title} => document title

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

The first two are easy, obviously, but I am struggling with the third. The only thing I can think of is to do the replacements of all those that don't have a colon and then any which do have a colon, to trigger a function.

4

1 に答える 1

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);
}
于 2012-07-24T14:01:46.250 に答える