如何用正则表达式把目标替换成数组中的值?

来源:百度知道 编辑:UC知道 时间:2024/06/18 03:43:29
数组数据:

Array
(
[articleid] => 1
[time] => 2009-11-22 05:11:52
)

// 测试数据:
$teststr = "<li>[field:time /]</li>";

// 正则表达式:
$pattern = "(\[field:(\w*) /\])";

// 测试过程
$tempstr = preg_replace($pattern,$arr['\\1'],$teststr);

// 输出结果
echo($tempstr);

输出结果发现总是空值,怀疑 $arr['\\1'] 里面的 \\1 并没有被匹配的字符替换掉,请问应该如何处理?

如果是用javascript,这样的替换很容易,
因为 javascript 有这样的语法 str.replcae(/patern/, function(...) {...});

php 似乎不能内嵌匿名函数,所以这样的替换不大方便。

这样:

<?php
$arr = array(
'articleid' => 1,
'time' => '2009-11-22 05:11:52'
);

$teststr = "<li>[field:time /]</li>";

$pattern = '/\[field:(\w*)\s*\/\]/';

preg_match_all($pattern, $teststr, $matches, PREG_SET_ORDER);
print_r($matches);
foreach ($matches as $match) {
$teststr = str_replace($match[0], $arr[$match[1]], $teststr);
}

echo $teststr."\n";