php替换非法字符,PHP – 字符串替换SyntaxError:非法字符

$status的输出

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'

解决方法:

之所以发生这种情况,是因为您还要替换之前替换的颜色代码中的数字.

解决方案:在插入颜色数组之前遍历数组以进行替换:

// 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);

标签:str-replace,implode,php

来源: https://codeday.me/bug/20190724/1526791.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值