$xcatname = 'Business';
$repeatmaincitiescat = 'London, Paris, New York';
$repeatmaincitiescat = str_replace(',', ' ' . $xcatname . ',', $repeatmaincitiescat).(empty($repeatmaincitiessubcat)?'':"");
上面给出此结果的代码:伦敦商业, 巴黎商业, 纽约商业
但是,我想要这种类型的输出,
伦敦商务, 巴黎商务, 纽约商务
我尝试了一些更改,但结果是错误的。
简单的映射呢?
$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;}
}
hakre 提出的另一种方法是使用正则表达式。它尽可能接近您的代码,您想要实现的目标无法通过简单的替换来完成。
所以,你可以做(尽可能接近你所做的):
<?php
$xcatname = 'Business';
$repeatmaincitiescat = 'London, Paris, New York';
$pattern = '/([^,]+)((,'s*)*)/';
function replace_match($matches) {
global $xcatname;
return $xcatname . ' in ' . $matches[1] . $matches[2];
}
$processed = preg_replace_callback($pattern, "replace_match", $repeatmaincitiescat);
// or simpler:
// $processed = preg_replace($pattern, $xcatname . " in $1$2", $repeatmaincitiescat);
?>
$xcatname = 'Business in';$repeatmaincitiescat = '伦敦、巴黎、纽约';
$repeatmaincitiescat = "$xcatname ".str_replace(',',','.$xcatname.'', $repeatmaincitiescat)。(空($repeatmaincitiessubcat)?'':");
echo $repeatmaincitiescat ;