substr_replace函数,substring函数用法

http://www.itjxue.com  2023-01-17 04:08  来源:未知  点击次数: 

一个关于PHP中substr_replace函数的问题

问了一大串问题才10分,

1、输出结果为“用明日的辛勤工作,换未来的百倍回报!”,为什么"明日"替换的是

"今日"两个字呢

A: echo substr_replace('',"明日",2,-30);

这句的意思是,从第二个字符'今'开始替换,直到-30,负数代表从末端开始往头数的第30个字符时“停止替换”,刚刚替换完'明日',就到-30了,整个长度是+/-36,

==========

2、但是substr_replace函数并没有明确的指明要去替换哪个。

A:这个函数功能是“替换子串”,过程是先得到子串(即和substr功能相同),再把字串用给的'明日'替换(和str_replace相同)

====

3、那么echo substr_replace("abcd","h",2)从哪里开始替换?

A:套用2的回答,先取得子串, 'abcd'从2个位置到末尾,得子串'cd',子串'cd'换成'h',并回去得结果'ah'.

===============

4、这个例子是要用逗号去替换空格,里面的start为什么是44呢

这个44是怎么算出来的而 length怎么是1呢,length不是代表返回的字符串的长度吗?

A:这段文字用的gbk编码,每个汉字2个字节。中间的空格位置从0算起是44,

length是取的子串长度,不是返回长度,取1个长度的子串就是一个空格,把空格替换成逗号

php的substr_replace()和str_replace()有什么不同啊,都是吧字符串一部分替换'

区别在于:

1.substr_replace():把字符串的一部分替换为另一个字符串.

str_replace():使用一个字符串替换字符串中的另一些字符

substr_replace()??用于把字符串的一部分替换为另一个字符串,返回混合类型。

语法:

mix?substr_replace?(?mixed?string,?string?replacement,?int?start?[,?int?length]?)

例如:

?php

echo substr_replace('abcdef', '###', 1); //输出 a###

echo substr_replace('abcdef', '###', 1, 2); //输出 a###def

echo substr_replace('abcdef', '###', -3, 2); //输出 abc###f

echo substr_replace('abcdef', '###', 1, -2); //输出 a###ef

?

注意:如果 start 是负数且 length 小于等于 start ,则 length 为 0。

str_replace()使用一个字符串替换字符串中的另一些字符,返回混合类型。

语法:

mixed str_replace( mixed search, mixed replace, mixed string [, int count] )

例如:

?php

echo str_replace("world","earth","Hello world!"); //输出 Hello earth!

//替换多个,且第二个参数为空字符

echo str_replace("o","","Hello world!"); //输出 Hell wrld!

//使用数组

$arr = array("e", "o");

$arr2 = array("x", "y");

echo str_replace($arr, $arr2, "Hello World of PHP", $i); //输出 Hxlly Wyrld yf PHP

echo $i; //输出4 ?

?

注意:1.该函数与 substr_replace() 不同之处是满足条件的都进行替换

? ? ? ? 2.该函数对大小写敏感。如需进行大小写不敏感的查找替换,请使用 str_ireplace()

substr_replace — 替换字符串的子串?

下面是总结后的知识点,希望帮到你!

substr_replace

(PHP 4, PHP 5, PHP 7, PHP 8)

substr_replace — 替换字符串的子串

说明

substr_replace ( mixed $string , mixed $replacement , mixed $start , mixed $length = ? ) : mixed

substr_replace() 在字符串 string 的副本中将由 start 和可选的 length 参数限定的子字符串使用 replacement 进行替换。

参数

string

输入字符串。

An array of strings can be provided, in which case the replacements will occur on each string in turn. In this case, the replacement, start and length parameters may be provided either as scalar values to be applied to each input string in turn, or as arrays, in which case the corresponding array element will be used for each input string.

replacement

替换字符串。

start

如果 start 为正数,替换将从 string 的 start 位置开始。

如果 start 为负数,替换将从 string 的倒数第 start 个位置开始。

length

如果设定了这个参数并且为正数,表示 string 中被替换的子字符串的长度。如果设定为负数,它表示待替换的子字符串结尾处距离 string 末端的字符个数。如果没有提供此参数,那么它默认为 strlen( string ) (字符串的长度)。当然,如果 length 为 0,那么这个函数的功能为将 replacement 插入到 string 的 start 位置处。

(责任编辑:IT教学网)

更多

推荐其它系统文章