<?php
error_reporting(-1);
class Replacer
{
public function __construct(array $args = NULL)
{
if (!empty($args)) {
foreach ($args as $name => $value) {
$this->$name = $value;
}
}
}
public function buildString($text)
{
$parts = preg_split('/(\{\$.+\})/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$ret = '';
foreach ($parts as $sub) {
if (substr($sub, 0, 2) != '{$' || substr($sub, -1, 1) != '}') {
$ret .= $sub;
} else {
// something like {$name}
$sub = substr($sub, 2, -1);
if (($p = strpos($sub, ':')) === FALSE) {
$ret .= $this->$sub;
} else {
// something like {$name:6,3}
list($from, $to) = explode(',', substr($sub, $p + 1));
$sub = substr($sub, 0, $p);
$ret .= substr($this->$sub, intval($from), intval($to));
}
}
}
return $ret;
}
}
$r1 = new Replacer(array(
'uploadDir' => './upload/',
'rand9' => sprintf('%03d%03d%03d', mt_rand(0, 999), mt_rand(0, 999), mt_rand(0, 999))));
echo $r1->buildString('{$uploadDir}{$rand9:0,3}/{$rand9:3,3}/{$rand9:6,3}.dat') . "<br/>\n";
$r2 = new Replacer(array(
'avatarDir' => './img/avatars/',
'userId' => 4021));
echo $r2->buildString('{$avatarDir}{$userId}.jpg') . "<br/>\n";
выводит
./upload/362/246/480.dat
./img/avatars/4021.jpg