php str_replace 正则表达式,php中str_replace函数的多种用法总结

函数原型:mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

这个函数的三个参数类型都是mixed,所以它们都既可以是字符串,也可以是数组,因此就有以下几种用法:

1、 $search和$replace都是字符串,这是最常见的用法

echo str_replace("a", "apple", "This is a demo.");

输出:This is apple demo.

2、$search为数组,对$search中的数组元素逐个替换成$replace,最终输出为字符串。

echo str_replace(array("a", "p","o"), "apple", "This is a demo.");

输出:This is aappleapplele demapple.

3、$replace为数组,会报错且不会输出预想的结果,不建议使用

echo str_replace("a",  array("apple", "pear"), "This is a demo.");

输出:This is Array demo.并报错Notice: Array to string conversion

4、$subject为数组,$subject中的每个数组元素都会做一次独立替换,最终输出为数组。

print_r(str_replace("a", "apple", array("This is a demo.", "This is not a demo.")));

输出:Array ( [0] => This is apple demo. [1] => This is not apple demo. )

5、$search和$replace都为数组,这时又可以分为三种情况:

a).$search和$replace一样长,则相同下标对应替换

b).$search比$replace长,则$search中比$replace多出的数组元素都被替换成空字符串

c).$search比$replace短,则$replace中多出的数组元素被忽略

echo str_replace(array("a", "o"), array("apple", "pear"), "This is a demo.");

输出:This is apple dempear.

6、$search、$replace和$subject都为数组,这是以上多种情况的综合

print_r(str_replace(array("a", "o"), array("apple", "pear"), array("This is a demo.", "This is not a demo.")));

输出:Array ( [0] => This is apple dempear. [1] => This is npeart appledempear. )

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值