简体   繁体   中英

How can I replace exact match in preg_replace?

How can I replace a text with the exact match from the database?

<?php
class R {
  public $db = ['title'=>'Site Title'];
  function r($r) {
    $r = preg_replace('~{% site:(.+?) %}~', $this->db[$1], $r);
    return $r;
  }
}

$R = new R();
$R->r('This is the site title: {% site:title %}');
?>

Return parse error: : syntax error, unexpected integer "1"

Thanks @Barmar , I got it solved using preg_replace_callback()

<?php
class R {
  public $db = ['title'=>'Site Title'];
  function r($r) {
    return preg_replace_callback('~{% site:(.+?) %}~', function($match) {
      return $this->db->$match[1];
    }, $r);
  }
}

$R = new R();
$R->r('This is the site title: {% site:title %}');
?>

And here I replaced both.

<?php
class R {
  public $site = ['title'=>'Site Title'];
  public $repl = ['name'=>'Replacement Name'];
  function r($r) {
    return preg_replace_callback('~{% (.+?):(.+?) %}~', function($match) {
      return $this->$match[1][$match[2]];
    }, $r);
  }
}

$R = new R();
$R->r('This is the site title: {% site:title %} and here is the replacement name: {% repl:name %}');
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM