【函数功能】
该函数把指定字符串的指定部分替换为另一个字符串。
【函数语法】
substr_replace ($string, $replacement, $start, $length = null)
【参数说明】
$string:必需,要替换的字符串。
$replacement:必需,要插入或替换成的字符串。
$start:必需,在字符串的何处开始替换,有以下几种情况:
正数:在字符串中的指定位置开始替换。
负数:从字符串末端往前到start个字符的位置开始替换。
0:在字符串中的第一个字符处开始替换。
$length:可选,要替换多少个字符。默认是与字符串长度相同,传值有以下几种情况:
正数:被替换的字符串长度。
负数:表示从$start开始替换到距离字符串末端有$length个字符。
0:表示插入字符串到$start处。
【演示程序】
<?php
/**
* substr_replace ($string, $replacement, $start, $length = null)
* **/
$string = "Hello i am PHP!";
echo substr_replace($string, "Hi", 0);//默认参数:即从0开始替换整个字符串
echo "<br>";
echo substr_replace($string, "Hi", 0,5);//将前五个字符替换为Hi
echo "<br>";
echo substr_replace($string, "Java!", -4);//start为负数,将PHP替换为Java
echo "<br>";
echo substr_replace($string, "Java!", 0,-4);//length为负数,表示替换到距离字符串末端有length个字符
echo "<br>";
echo substr_replace($string, "Java,", 11,0);//length为0,表示插入字符串到$start处
?>
【输出结果】
Hi
Hi i am PHP!
Hello i am Java!
Java!PHP!
Hello i am Java,PHP!
【特别注意】
1.如果 start 参数是负数且 length 小于或者等于 start,则 length 为 0。
2.该函数是二进制安全的,替换中文时需注意:在utf-8下一个中文3个字符,在gbk下2个字符。
3.PHP 版本:4+。
4.更新日志:自 PHP 4.3.3 起,所有参数都接受数组。
【原版定义】
/**
* Replace text within a portion of a string
* @link http://www.php.net/manual/en/function.substr-replace.php
* @param string mixed <p>
* The input string.
* </p>
* <p>
* 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.
* </p>
* @param replacement mixed <p>
* The replacement string.
* </p>
* @param start mixed <p>
* If start is positive, the replacing will
* begin at the start'th offset into
* string.
* </p>
* <p>
* If start is negative, the replacing will
* begin at the start'th character from the
* end of string.
* </p>
* @param length mixed[optional] <p>
* If given and is positive, it represents the length of the portion of
* string which is to be replaced. If it is
* negative, it represents the number of characters from the end of
* string at which to stop replacing. If it
* is not given, then it will default to strlen(
* string ); i.e. end the replacing at the
* end of string. Of course, if
* length is zero then this function will have the
* effect of inserting replacement into
* string at the given
* start offset.
* </p>
* @return mixed The result string is returned. If string is an
* array then array is returned.
*/
转载请注明出处:php1234.cn ,原文地址:http://www.php1234.cn/a/functions/2016/0926/77.html