PHP - 为模板创建自定义变量

时间:2013-02-16 03:08:19

标签: php regex

我不知道该怎么说,我会用一个例子。

//[$var:Username|n] will print username with n length
$myText = 'The participants are [$var:Username|10], [$var:Username|8], and [$var:Username|6]';
$username = array('Alexandrite', 'Maximillian', 'Angelina');
$result = someFunction('[$var:Username|n]', $username, $myText);
echo $result;
//The participants are Alexandrit, Maximill, and Angeli

知道怎么做吗?也许使用preg_replace?

1 个答案:

答案 0 :(得分:3)

我很想知道为什么你甚至需要这样做。无论:

preg_replace_callback('/\[\$var:Username\|(\d+)\]/', function ($match)
    use (&$count, $username
) {
    return substr($username[$count++], 0, $match[1]);
}, $myText);