简体   繁体   English

如果键来自php中preg_replace中的正则表达式,如何引用键->值

[英]how reference a key-> value if a key is from a regular expression in preg_replace in php

Having this array: 具有此数组:

$arr['id']=150;
$arr['contenido']="un proyecto";
$arr['foto']="una foto";

This works very good 这个很好

$text = 'estamos en el registro {id} cuyo contenido es {contenido} por lo que veremos su {foto}';
$text = preg_replace('/{(.*?)}/', '$1', $text);
echo $text;

//print:
//estamos en el registro id cuyo contenido es contenido por lo que veremos su foto

I understand that $1 y the value enclosed by { and } but I need replace with the value of array that match with the key. 我知道$ 1是{和}括起来的值,但我需要替换为与键匹配的array的值。 I trying this 我尝试这个

$text2 ='estamos en el registro {id} cuyo contenido es {contenido} por lo que veremos su {foto}';

$text2 = preg_replace('/{(.*?)}/', $arr['$1'], $text2);
echo $text2;

//print
estamos en el registro  cuyo contenido es  por lo que veremos su 

but this no print anythig in the pos of {key}, how I get impresed the array value referenced by the key yn {}. 但这在{key}的位置上没有任何显示,我如何隐含键yn {}引用的数组值。

preg_replace_callback(
    '/{(.*?)}/',
    function (array $m) use ($arr) { return $arr[$m[1]]; },
    $text2
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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