2014-09-04 142 views
0

我想訂購一個字符串,以便首字母大寫。爲了讓它更難,遵循另一個變量的模式會很好。由另一個字符串排序字符串,大寫字母第一個

可以說我有

$x = "FAcfAC"; 

,我想首先在字符的順序

$y = "FAC"; 

用大寫字母先訂購然後,這樣的結果是

$result = "FfAACc" 
+0

分割的字符串轉換成使用數組str_split(),可以使用許多陣列排序方法由另一個數組的值進行排序的一個(例如http://stackoverflow.com/questions/348410/sort-an -array-based-on-another-array),然後使用implode重建字符串 – 2014-09-04 18:38:29

回答

0

就像這樣,唯一的缺點是,如果字符不包含在$y它將被排除在原始字符串之外。

<?php 

$x = 'FAcfAC'; 
$y = 'FAC'; 
$result = ''; 

$yLength = strlen($y); 

for ($i = 0; $i < $yLength; $i++) 
{ 
    $char = $y{$i}; 
    $upper = strtoupper($char); 
    $lower = strtolower($char); 

    if ($count = substr_count($x, $upper)) 
    { 
     $result .= str_repeat($upper, $count); 
    } 

    if ($count = substr_count($x, $lower)) 
    { 
     $result .= str_repeat($lower, $count); 
    } 
} 

echo $result; 
相關問題