一个简单的映射呢?
$xcatname = 'Business in %s';
$repeatmaincitiescat = 'London, Paris, New York';
$separator = ', ';
$repeatmaincitiescat = implode(
$separator,
array_map(function($v) use ($xcatname) {
return sprintf($xcatname, $v);
},
explode($separator, $repeatmaincitiescat))
);
echo $repeatmaincitiescat;
输出:
Business in London, Business in Paris, Business in New York
这里有一个 PHP 5.2 变体:
$xcatname = 'Business in %s';
$repeatmaincitiescat = 'London, Paris, New York';
$new = new MaskRepeat($repeatmaincitiescat, ', ', $xcatname);
echo $new; # Business in London, Business in Paris, Business in New York
class MaskRepeat {
private $str;
public function __construct($string, $separator, $mask) {
$array = explode($separator, $string);
foreach($array as &$value) {
$value = sprintf($mask, $value);
}
$this->str = implode($separator, $array);
}
public function __toString() {return $this->str;}
}