1", "b>0");$str = preg_replace("/#(\w+)/","\$items[$1]",$a);echo $str">
当前位置:Gxlcms > PHP教程 > preg_replace-php中怎么把变量中隐藏的变量解析出来?

preg_replace-php中怎么把变量中隐藏的变量解析出来?

时间:2021-07-01 10:21:17 帮助过:31人阅读

$a = " #0 and #1 or (#0)";
$items = array(
    "a>1",
    "b>0"
);
$str = preg_replace("/#(\w+)/","\$items[$1]",$a);
echo $str;

输出结果: $items[0] and $items[1] or ($items[0])

怎么才能让输出结果是:a>1 and b>0 or (a>1)?
请各位大神帮忙看一下,谢谢!

回复内容:

$a = " #0 and #1 or (#0)";
$items = array(
    "a>1",
    "b>0"
);
$str = preg_replace("/#(\w+)/","\$items[$1]",$a);
echo $str;

输出结果: $items[0] and $items[1] or ($items[0])

怎么才能让输出结果是:a>1 and b>0 or (a>1)?
请各位大神帮忙看一下,谢谢!

正则

$items = [
    'a > 1',
    'b > 0',
    'abc' => 'c > 1'
];
$subject = '#0 and #1 or (#0) and #abc #nooo';
echo preg_replace_callback('/#([a-z0-9_]+)/i', function($v) use ($items){
    return isset($items[$v[1]]) ? $items[$v[1]] : $v[0];
}, $subject);
a > 1 and b > 0 or (a > 1) and c > 1 #nooo

人气教程排行