str_replace 4个用法及与strtr区别

//实例一:字符串替换字符串
$str1 = str_replace("red","black","red green yellow pink purple");
echo $str1;    //输出结果为black green yellow pink purple


//实例二:字符串替换数组键值(替换多个)
$arr = array("blue","red","greenred","yellow");
$str1 = str_replace("red","pink",$arr,$i);
print_r($str1);


//实例三:数组替换数组,映射替换
$arr1 = array("banana","orange");
$arr2 = array("pitaya","tomato");
$con_arr = array("apple","orange","banana","grape");
$con_rep = str_replace($arr1,$arr2,$con_arr,$count);
print_r($con_rep);


//实例四:如$search为数组,$replace为字符串时
$search = array("banana","grape");
$replace = "tomato";
$arr = array("banana","apple","orange","grape");
$new_arr = str_replace($search,$replace,$arr,$count);
print_r($new_arr);



另:
#str_replace 与 strtr 替换区别
# 在上一次基础上替换
$url = 'http://www.baidu.com/aaa/bbb/index.html'; 
$arr1 = ['.com','.cn']; 
$arr2 = ['.cn','.bc']; 
$url = str_replace($arr1,$arr2,$url);
echo $url,"\n";


# 最原始的那个字符串
$url = 'http://www.baidu.com/aaa/bbb/index.html'; 
echo strtr($url, ['.com'=>'.cn', '.cn' => '.bc']),"\n";


#strtr  strtr(string,from,to)与 strtr(string,array) 区别
#strtr(string,from,to)是逐个字符替换,而strtr(string,array)是字符串替换
echo strtr($url,'.com','.cn'),"\n";
echo strtr($url,['.com' => '.cn']),"\n";

#strtr("aidenliu","ai","") 不发生替换(第二个参数为零长度字符串)
#strtr("aidenliu",array("ai"=>"")) 发生替换

#结论:strtr(string,from,to)基本不会用到;strtr(string,array)使用较多。而且你想到替换什么你就往数组加什么,比较方便

 

  • 0
    点赞
  • 0
    评论
  • 1
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

打赏
文章很值,打赏犒劳作者一下
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页

打赏

精神小伙2号

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者