Home  >  Article  >  Backend Development  >  The function substr_replace() that replaces part of a php string with another string

The function substr_replace() that replaces part of a php string with another string

黄舟
黄舟Original
2017-11-06 13:42:482812browse

Example

Replace "Hello" with "world":

<?php
echo substr_replace("Hello","world",0);
?>

Definition and usage

substr_replace() function replaces the string Replace part of it with another string.

Note: If the start parameter is negative and length is less than or equal to start, length is 0.

Note: This function is binary safe.

Syntax

substr_replace(string,replacement,start,length)
Parameters Description
string Required. Specifies the string to check.
replacement Required. Specifies the string to be inserted.
start Required. Specifies where in the string to begin replacement.
  • Positive number - starts at the specified position in the string

  • Negative number - starts at the specified position from the end of the string

  • 0 - Starts at the first character in the string

length Optional. Specifies how many characters to replace. The default is the same as the string length.
  • Positive number - the length of the string to be replaced

  • Negative number - the number of characters to be replaced from the end of the string

  • 0 - Insert instead of replace

Technical details

As of PHP 4.3.3, all parameters accept arrays.

更多实例

实例 1

从字符串的第 6 个位置开始替换(把 "world" 替换成 "earth"):

<?php
echo substr_replace("Hello world","earth",6);
?>

实例 2

从字符串结尾的第 5 个位置开始替换(把 "world" 替换成 "earth"):

<?php
echo substr_replace("Hello world","earth",-5);
?>

实例 3

在 "world" 开头插入 "Hello":

<?php
echo substr_replace("world","Hello ",0,0);
?>

实例 4

一次性替换多个字符串。把每个字符串中的 "AAA" 替换成 "BBB":

<?php
$replace = array("1: AAA","2: AAA","3: AAA");
echo implode("<br>",substr_replace($replace,&#39;BBB&#39;,3,3));
?>

例子:

<?php
echo substr_replace(&#39;abcdef&#39;, &#39;###&#39;, 1);	//输出 a###
echo substr_replace(&#39;abcdef&#39;, &#39;###&#39;, 1, 2);	//输出 a###def
echo substr_replace(&#39;abcdef&#39;, &#39;###&#39;, -3, 2);	//输出 abc###f
echo substr_replace(&#39;abcdef&#39;, &#39;###&#39;, 1, -2);	//输出 a###ef 
?>


Return value: Return the replaced string. If string is an array, the array is returned.
PHP Version: 4+
##Update Log :

The above is the detailed content of The function substr_replace() that replaces part of a php string with another string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn