2012-04-13 54 views
0
$xcatname = 'Business'; 
$repeatmaincitiescat = 'London, Paris, New York'; 

$repeatmaincitiescat = str_replace(',', ' ' . $xcatname . ',', $repeatmaincitiescat).(empty($repeatmaincitiessubcat)?'':""); 

給這個結果上面的代碼:倫敦業務,巴黎商業,紐約商業重複並把在一個字上一個PHP變量

不過,我想這種類型的輸出,

在倫敦的商業,在巴黎的商業,在紐約的商業

我試了一些改變,但事實證明是錯誤的。

回答

1

到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); 
?> 
+0

太棒了,它效果很好,謝謝jadkik94 – Mas 2012-04-13 23:10:06

2

簡單映射怎麼樣?

$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;} 
} 
+0

我試過結果是在語法錯誤?語法錯誤,意外的T_FUNCTION,期待')'在 – Mas 2012-04-13 22:23:04

+0

@Mas:好吧,PHP 5.2我假設你正在使用。讓我思考一下最好的......。 – hakre 2012-04-13 22:25:15

+0

如果您可以通過修改上面的代碼使其工作,我將不勝感激,您只需更改變量的回顯順序即可。 – Mas 2012-04-13 22:28:10

0

$ xcatname = '業務中'; $ repeatmaincitiescat ='倫敦,巴黎,紐約'; $ redmaincitiescat =「$ xcatname」.str_replace(',',','。$ xcatname。'',$ repeatmaincitiescat)。(empty($ repeatmaincitiessubcat)?'':「」);

echo $repeatmaincitiescat ;