注册/登录 搜索

02408自媒体免费建站系统

博客、文章系统、商城、企业网站、个性化论坛等随心变

免费商业博客管理系统

自媒体创业,自媒体运营,一个空间2个网站的全能型博客系统

个人博客系统免费下载

教你自媒体怎么赚钱的免费自媒体博客自媒体平台
投稿 • 技术咨询

当前位置:首页 -> 网络技术 -> 免费PHP教程 -> 文章正文

substr_replace与str_replace的区别,以及用php函数在字符串指定位置插入新字符或关键词替换

发布者:江湖一道杠  Time:  阅读数:?substr-replace和str-replace区别
x

php函数substr_replace和str_replace的都可以实现关键字替换功能,例如把字符串World替换成Beijing:


1. 用substr_replace函数实现替换关键词方法
<?php
$str1 = 'Hello World';
$str2 = 'Beijing';
echo substr_replace($str1 , $str2 , 6);
?>
输出结果:Hello Beijing


<?php
$str1 = 'Hello World';
$str2 = 'Beijing';
echo substr_replace($str1 , $str2 , -5);
?>
输出结果:Hello Beijing

2. 用str_replace函数实现替换关键词方法
<?php
$str1 = 'World';
$str2 = 'Beijing';
$str3 = 'Hello World';
echo str_replace($str1 , $str2 , $str3);
?>
输出结果:Hello Beijing

但是substr_replace与str_replace还是有很大区别的。
首先str_replace函数替换字符串是区分大小写的,把字符串 "Hello world!" 中的字符 "WORLD"(不区分大小写)替换成 "Beijing"就需要使用str_ireplace函数(两个PHP函数的区别在于str_replace比str_ireplace少一个字母i),例如:
<?php
echo str_ireplace("WORLD","Beijing","Hello world");
?>
输出结果:Hello Beijing

如果把上面的str_ireplace函数替换成str_replace函数,字符串将不会被替换:
<?php
echo str_replace("WORLD","Beijing","Hello world");
?>
输出结果:Hello world (没有被替换)

substr_replace与str_replace或str_ireplace函数的区别更在于str_replace函数只能实现相匹配的关键字或字符串替换,否则不予替换,而substr_replace函数不但能实现任何关键字替换,而且还能实现在指定的位置进行对任何字符串的替换或插入,例如:

1. 将Hello World字符串中World字符串替换成Beijing:
<?php
$str1 = 'Hello World';
$str2 = 'Beijing';
echo substr_replace($str1 , $str2 , 6);
?>
输出结果:Hello Beijing

2. 在Hello World!字符串中插入Beijing And字符串
<?php
$str1 = 'Hello World!';
$str2 = ' Beijing And';
echo substr_replace($str1 , $str2 , 5 , 0);
?>
输出结果:Hello Beijing And World!

这里主要简单说明了substr_replace与str_replace的区别,以及用php函数在字符串指定位置插入新字符或关键词替换方法,您还可以尝试更多复杂情况下的关键字替换和插入操作,发现更多规律。

本文地址:http://www.02408.com/p-substr-replace和str-replace区别.html

评论专区:

名 称必填

邮 箱必填

网 址选填

验 证

添加表情

最新评论

暂无回答
    江湖一道杠

    专题/发布者:

    置顶信息

  1. 反全球化,区域合作和地缘经济对中国更有利!
  2. 中美开战中国能坚持几个小时?
  3. 春捂秋冻指的是什么意思?为什么说春冻骨头秋冻肉?春冻骨头秋冻肉是什么意思?为什么说春捂秋冻不生杂病
  4. TikTok贱卖微软字节跳动一毛钱都拿不到
  5. 国务院:大力培育集成电路领域和软件领域企业
  6. 2019年中国农民人均纯收入多少钱 2019年中国最低农民可支配收入多少钱
  7. 90%零部件依赖中国!印度抵制下,印企或借道日韩采购自华商品
  8. 中国巨头海外大撤退
  9. 更多..

    按标签查询

    更多..

    按时间查询

    2023年07月(1)2023年01月(1)2022年11月(1)2021年11月(1)2021年05月(2)2021年04月(1)2021年01月(1)2020年11月(1)2020年10月(7)2020年09月(2)2020年08月(35)2020年07月(108)2020年06月(240)2020年05月(117)2020年04月(2)2020年03月(6)2020年02月(3)2020年01月(1)

    网站分类:

    智库声音

    网络技术

    创业赚钱

    网络热点

    钻石戒指珠宝首饰

    谷歌广告


    Notice: Undefined variable: ad7 in /www/wwwroot/www_02408_com/system/compiled/Aid.php on line 209