簡單映射怎麼樣?
$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;}
}
太棒了,它效果很好,謝謝jadkik94 – Mas 2012-04-13 23:10:06