2015-09-28 130 views
3

输出为$状态PHP - 字符串替换语法错误:非法字符

Array 
(
    [1] => 1 
    [2] => 0 
    [3] => 0 
    [4] => 4 
    [5] => 4 
) 

$color_code_string = implode(",",$status); 

输出继电器

1,0,0,4,4 

$color_code_string = str_replace("0","'#F00'",$color_code_string); 
$color_code_string = str_replace("1","'#00bcd4'",$color_code_string); 
$color_code_string = str_replace("2","'#4caf50'",$color_code_string); 
$color_code_string = str_replace("3","'#bdbdbd'",$color_code_string); 
$color_code_string = str_replace("4","'#ff9900'",$color_code_string); 

异常

SyntaxError: illegal character 
colors: ['#00bcd'#ff9900'','#F00','#F00','#ff9900','#ff9900'] 

//prints '#00bcd'#ff9900'','#F00','#F00','#ff9900','#ff9900' 

如何实现预期的输出如下

'#00bcd','#ff9900','#F00','#F00','#ff9900','#ff9900' 

回答

5

那是因为你还颜色代码内更换号码你之前更换过。 解决方案:

// Translation table, saves you separate lines of stringreplace calls. 
$colorCodes = array(
    0 => "#F00", 
    1 => "#00bcd4", 
    2 => "#4caf50", 
    3 => "#bdbdbd", 
    4 => "#ff9900", 
); 

// Build an array of colors based on the array of status codes and the translation table. 
// I'm adding the quotes here too, but that's up to you. 
$statusColors = array(); 
foreach($status as $colorCode) { 
    $statusColors[] = "'{$colorCodes[$colorCode]}'"; 
} 

// Last step: implode the array of colors. 
$colors = implode(','$statusColors); 
1

有关于在str_replace() documentation您的问题一大注意事项:

Caution Replacement order gotcha

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document. Use strtr() instead, because str_replace() will overwrite previous replacements

$status = [ 
    1, 
    0, 
    0, 
    4, 
    4, 
]; 

$color_code_string = implode(",",$status); 

$replacements = [ 
    "0" => "'#F00'", 
    "1" => "'#00bcd4'", 
    "2" => "'#4caf50'", 
    "3" => "'#bdbdbd'", 
    "4" => "'#ff9900'", 
]; 


$color_code_string = strtr($color_code_string, $replacements); 
echo $color_code_string; 
2
$status = [1,0,0,4,4,]; 
$color_code_string = implode(",",$status); 
$replacements = ["0" => "'#F00'","1" => "'#00bcd4'","2" => "'#4caf50'","3" => "'#bdbdbd'","4" => "'#ff9900'",]; 
$color_code_string = strtr($color_code_string, $replacements); 
echo $color_code_string; 
0
<?php 
$color_code = array(1, 0, 0, 4, 4); 

array_walk($color_code, 'color_code_replace'); 
$color_code_string = implode(",",$color_code); 

function color_code_replace(&$cell) { 
    switch ($cell) { 
     case 0 : { 
      $cell = '#F00'; 
      break; 
     } 
     case 1 : { 
      $cell = '#00bcd4'; 
      break; 
     } 
     case 2 : { 
      $cell = '#4caf50'; 
      break; 
     } 
     case 3 : { 
      $cell = '#bdbdbd'; 
      break; 
     } 
     case 4 : { 
      $cell = '#ff9900'; 
      break; 
     } 
     default : { 
      throw new Exception("Unhandled Color Code"); 
     } 
    } 
} 

var_dump($color_code); 
:遍历数组内爆的颜色阵列之前做更换