PHP substr_replace() Function Explained
The substr_replace() function is used to replace a portion of a string with another string. It is a commonly used function in PHP for string manipulation, allowing for flexible replacement of specific parts of the target string.
Syntax
substr_replace(str, replacement, begin, len)
Parameters
- str - The target string to be checked.
- replacement - The string that will replace part of the target string.
- begin - The starting position for replacement:
- If begin is a positive number, replacement starts from the specified position in the string.
- If begin is a negative number, replacement starts from the end of the string moving backwards.
- If begin is 0, replacement starts from the first character of the string.
- len - The number of characters to replace (optional). If not specified or set to the default value, replacement continues until the end of the string.
- If len is positive, it specifies how many characters to replace.
- If len is negative, it keeps that many characters at the end of the string and replaces the rest.
- If len is 0, the function inserts the replacement string without replacing any characters.
Return Value
The substr_replace() function returns the string after replacement.
Example 1: Replacing a Portion of the String
The following code demonstrates how to replace a part of a string starting from a specified position:
<?php
echo substr_replace("Demo text", "word", 5);
?>
Output
Demo word
Example 2: Replacing from the End of the String
This example shows how to replace a portion of the string starting from the end:
<?php
echo substr_replace("Demo text", "word", -5);
?>
Output
Demoword
Conclusion
From the above examples, we can see that the PHP substr_replace() function is versatile and allows for flexible string replacement, whether starting from the beginning, middle, or end of the string. It is an essential function for efficient string manipulation in PHP.