PHP Tutorial - PHP substr_replace() Function






Definition

The substr_replace() function replaces one string with another string.

Syntax

PHP substr_replace() Function has the following syntax.

substr_replace(string,replacement,start,length)

Parameter

ParameterIs RequiredDescription
stringRequired.String to check
replacementRequired.String to insert
startRequired.Where to start replacing in the string
  • A positive number - Start replacing at the specified position in the string
  • Negative number - Start replacing at the specified position from the end of the string
  • 0 - Start replacing at the first character in the string
lengthOptional.Specifies how many characters should be replaced.
  • Default is the same length as the string.
  • A positive number - The length of string to be replaced
  • A negative number - How many characters should be left at end of string after replacing
  • 0 - Insert instead of replace

Return

PHP substr_replace() Function returns the replaced string. If the string is an array then the array is returned.





Example 1

Replace "Hello" with "world":


<?php
echo substr_replace("Hello world from java2s.com","world",0);
?>

The code above generates the following result.

Example 2

Start replacing at the 6th position in the string (replace "world" with "earth"):


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

The code above generates the following result.





Example 3

Start replacing at the 5th position from the end of the string (replace "world" with "earth"):


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

The code above generates the following result.

Example 4

Insert "Hello" at the beginning of "world":


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

The code above generates the following result.

Example 5

Replace multiple strings at once. Replace "AAA" in each string with "BBB":


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

The code above generates the following result.