PHP substr_replace() Function

PHP substr_replace() Function

The substr_replace() function in PHP replaces a part of a string with another string.

Syntax

substr_replace (mixed $string , mixed $replacement , mixed $start [, mixed $length ] )

Parameter

string(required)- This parameter represents the input string.

replacement(required)- This parameter signifies the string to replace with.

start(required)- It signifies where to start replacing in the string.

  • It start is positive(0<), the replacing will begin at the specified position in the string.
  • If start is negative(0>), the replacing will begin at the specified position from the end of the string.
  • If start is equal to 0, the replacing will begin at the first character in the string.

length(optional)- This parameter specifies how many characters should be replaced.

  • If length is positive(0<), it represents the length of the portion of string which is to be replaced.
  • If length is negative(0>), it represents the number of characters from the end of the string at which to stop replacing.
  • If length is equal to 0, it inserts instead of replacing.

Return

This function returns the replaced string, but if the string is an array, then the array is returned.

Example 1

 

Output

Actual String: Hello world
After replacing the string... 
New String: Hello PHP 

Example 2

 

Output

Actual String: Hello world
After replacing the string... 
New String: HelloPHP 

Example 3

 

Output

Actual String: Hello world
After replacing the string... 
New String: PHPHello world 

Example 4

 

Output

Actual String: Hello world
After replacing the string... 
New String: PHPHello world 

Example 5

 

Output

1: BBBPP
2: BBBHP
3: BBBHP