PHP substr_replace() Function
Topic: PHP String ReferencePrev|Next
Description
The substr_replace()
function replaces text within a portion of a string.
The following table summarizes the technical details of this function.
Return Value: | Returns the replaced string. If string is an array then array is returned. |
---|---|
Version: | PHP 4+ |
Syntax
The basic syntax of the substr_replace()
function is given with:
The following example shows the substr_replace()
function in action.
Example
Run this code »<?php
// Sample strings
$str = "Fairyland";
$replacement = "Horror";
// Replacing the substring
echo substr_replace($str, $replacement, 0, 5);
?>
Parameters
The substr_replace()
function accepts the following parameters.
Parameter | Description |
---|---|
string | Required. Specifies the string to work on. |
replacement | Required. Specifies the replacement string. |
start | Required. Specifies the position in the string from where the replacement will begin. If it is negative, replacement will begin at the start'th character from the end of string. |
length |
Optional. Specifies 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 the If it is zero (
0 ) then this function will have the effect of inserting the replacement string into the main string at the given start position. |
Tip: You can also pass an array of strings to this function, in this case the replacements will occur on each string. The replacement, start and length parameters may also be provided as arrays, in which case the corresponding array element will be used for each input string.
More Examples
Here're some more examples showing how substr_replace()
function actually works:
In the following example portion of string starting from the 6th position till the end will be replaced.
Example
Run this code »<?php
// Sample strings
$str = "Fairyland";
$replacement = "tales";
// Replacing the substring
echo substr_replace($str, $replacement, 5);
?>
In the following example replacement start at the 4th position from the end of the string.
Example
Run this code »<?php
// Sample strings
$str = "Wonderland";
$replacement = " Woman";
// Replacing the substring
echo substr_replace($str, $replacement, -4);
?>
In the following example insertion will took place instead of replacement, because length is zero.
Example
Run this code »<?php
// Sample strings
$str = "Fairyland";
$substr = " Park";
// Inserting the substring
echo substr_replace($str, $substr, 9, 0);
?>
In the following example multiple string will be replaced at once using arrays.
Example
Run this code »<?php
// Sample inputs
$input = array("A: Apple", "B: Ball", "C: Cat");
$replacement = array("Airplane", "Bus", "Car");
// Replacing the substrings
echo implode("<br>",substr_replace($input, $replacement, 3));
?>