English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP substr_replace() Function Usage and Example

PHP String Manual

The substr_replace() function is used to replace a part of a string with another string.

Syntax

substr_replace(string,replacement,start,length)

Definition and Usage

 Replaces a substring in a copy of the string string with replacement, limited by the start and optional length parameters.

Return Value

 Returns the string with the substring between start and the optional length parameter replaced by replacement. If string is an array, it will also return an array.

Parameter

Serial NumberParameters and Description
1

string

Specify the string to be checked

2

replacement

Specify the string to be replaced

3

start

If start is positive, the replacement will start from the start position of the string.
If start is negative, the replacement will start from the start position of the string in reverse.

4

length

If this parameter is set and is a positive number, it represents the length of the substring to be replaced in the string.

If set to a negative number, it represents the number of characters from the end of the string to the end of the substring to be replaced.

If this parameter is not provided, it defaults to strlen(string) (the length of the string).

Of course, if length is 0, then the function's functionality is to insert replacement into the start position of string.

Online Example

Try the following example, replacing the string from the specified position:

<?php
 //From the character position 6 starting from this position to replace (replace "world" with "PHP"):
 echo substr_replace("Hello world","PHP",6);
 echo '<br>';
 
 //Insert "Hello" at the beginning of "PHP"
 echo substr_replace("PHP","Hello",0,0);
?>
Test and see‹/›

Output Result

Hello PHP
Hello PHP

PHP String Manual