2012-11-19 62 views
0

我有這些代碼:PHP str_replace函數怪異的結果

$alphabet = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"); 

$first = array("Captain","Dirty","Squidlips","Bowman","Buccaneer","Two Toes","Sharkbait","Old","Peg Leg","Fluffbucket","Scallywag","Bucko","Dead man","Matey","Jolly","Stinky","Bloody","Miss","Mad","Red","Lady","Bretheren","Rapscallion","Landlubber","Wench","Freebooter"); 

ImageTTFText($image, 45, 0, 0, $y-intval("30"), imageColorAllocate($image,255,255,255), "pirate-font.ttf", str_replace($alphabet,$first,"bad")); 

請幫我解決這個奇怪的問題... 我覺得有什麼不對,他們我的編碼,但我不知道哪個是哪個...

通過上面的代碼...

據稱,輸出必須是Dirty Captain Bowman ,但奇怪的是,它輸出錯誤的結果...

檢查:http://alylores.x10.mx/106/pic.php

請幫我解決我的問題......

回答

3

不幸的是,從左到右的功能str_replace會導致這種情況。所以這裏是一個選擇。

這裏是下面的代碼的一個例子:Example.

$alphabet = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"); 

$first = array("Captain","Dirty","Squidlips","Bowman","Buccaneer","Two Toes","Sharkbait","Old","Peg Leg","Fluffbucket","Scallywag","Bucko","Dead man","Matey","Jolly","Stinky","Bloody","Miss","Mad","Red","Lady","Bretheren","Rapscallion","Landlubber","Wench","Freebooter"); 

// split bad into an array, each letter being its own value. 
$input = str_split('bad'); 

// Alphabet become the keys, $first are the values 
$c = array_combine($alphabet, $first); 

$output = ''; 
foreach ($input as $letter) 
{ 
    $output .= $c[$letter] . ' '; 
} 

$final_word = trim($output); 

ImageTTFText($image, 45, 0, 0, $y-intval("30"), imageColorAllocate($image,255,255,255), "pirate-font.ttf", $final_word); 
+0

thnx先生...我發現它的工作... XD –

+1

好交易。乾杯。 – wesside

2
<?php 
// Order of replacement 
$str  = "Line 1\nLine 2\rLine 3\r\nLine 4\n"; 
$order = array("\r\n", "\n", "\r"); 
$replace = '<br />'; 

// Processes \r\n's first so they aren't converted twice. 
$newstr = str_replace($order, $replace, $str); 

// Outputs F because A is replaced with B, then B is replaced with C, and so on... 
// Finally E is replaced with F, because of left to right replacements. 
$search = array('A', 'B', 'C', 'D', 'E'); 
$replace = array('B', 'C', 'D', 'E', 'F'); 
$subject = 'A'; 
echo str_replace($search, $replace, $subject); 

// Outputs: apearpearle pear 
// For the same reason mentioned above 
$letters = array('a', 'p'); 
$fruit = array('apple', 'pear'); 
$text = 'a p'; 
$output = str_replace($letters, $fruit, $text); 
echo $output; 
?> 

來源:http://php.net/manual/en/function.str-replace.php

僞代碼:

  1. 分割字符串數組(HTTP:// php.net/manual/en/function.str-split.php拆分長度= 1)
  2. 替換每個數組中的每個值嘗試
  3. 再次將字符串放在一起。
+1

另外有一個[大「注意」的文檔中的塊與本](http://bg2.php.net/manual/en /function.str-replace.php#refsect1-function.str-replace-notes)。 – lanzz

+0

你能修改我上面的代碼嗎? Y_Y –

+0

@JulianPaoloDayag這不是一個解決方案,只是一個解釋。它從php.net站點粘貼。 – wesside