PHP str_replace奇怪的结果

时间:2012-11-19 07:21:31

标签: php arrays gd str-replace explode

我有这些代码:

$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

请帮我解决问题...

2 个答案:

答案 0 :(得分: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); 

答案 1 :(得分: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. 替换每个arrayentry中的每个值
  3. 再把字符串放在一起。
相关问题