Hướng dẫn
Quảng cáo

Hàm substr-replace() trong PHP

Hướng dẫn cách sử dụng hàm substr-replace() trong lập trình PHP

Tác dụng của hàm substr-replace()

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+


The basic syntax of the substr_replace() function is given with:

substr_replace(string, replacement, start, length);

The following example shows the substr_replace() function in action.

// Sample strings
$str = "Fairyland";
$replacement = "Horror";

// Replacing the substring
echo substr_replace($str, $replacement, 0, 5);


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.

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 strlen(string); i.e. length of string.

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.

// 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.

// 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.

// 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.

// 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));

Bài viết này đã giúp ích cho bạn?

Bài viết mới