PHP preg_replace in foreach loop

I want to replace text, but dont work, plz help :slight_smile:

I am trying to use preg_replace in a foreach loop.

I need to replace all keywords wrapped between β€˜%’ and use the back reference.

For example, in my text I have few keywords like %author% %title% I need to replace the keywords so they look like $items->author and $items->title

  /**
     * Creates a new TemplateFillup model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */

  public function actionFillup()
   {
    $t_fillup = new TemplateFillup();
    $hasOne = Template::findOne(1);
    $t_fillup ->text = $template->text;
    //$t_fillup->template_id = $template->id;
    $values = TemplateFillupValues::find()->where(['template_id' => 1])->all();

    foreach ($values as $v) {

  
    $temp = $v->model::findOne($v->id);
    $t_fillup ->text = preg_replace($v->value, $temp->($v->field), $t_fillup->text);
    }
$t_fillup -> save();
}

The code above doesn’t clarify why you need back reference but this exact task could be done simpler:

$replacements = [
    '%author%' => $items->author,
    '%title%' => $items->title,
];

$result = strtr($text, $replacements);

Need replace from pgSQL(database) to another table :slight_smile: