If you’ve ever programmed then you know how important is manipulating strings and similar. One of the good quality of PHP is that it offers many functions that can easily modify strings. Here I will present you one of most useful php function (by my opinion) for manipulating strings called substr_replace( ). It permits many kinds of string modifications.
substr_replace() syntax
The function replaces the part of original indicated by the start (0 means the start of the string) and length values with the string new. If no fourth argument is given, substr_replace( ) removes the text from start to the end of the string.
$string = substr_replace(original, new, start [, length ]);
Basic Example
$greeting = “good morning citizen”;
$farewell = substr_replace($greeting, “bye”, 5, 7);
Value of a variable $farewell is “good bye citizen”
Insert String Without Deleting
Use a length of 0 to insert without deleting
$farewell = substr_replace($farewell, “kind “, 9, 0);
Value of a variable $farewell is “good bye kind citizen”
Delete part of string
Use a replacement of “” to delete without inserting.
$farewell = substr_replace($farewell, “”, 8);
Value of a variable $farewell is “good bye”
Insert at the beginning of the string
Here’s how you can insert at the beginning of the string:
$farewell = substr_replace($farewell, “now it’s time to say “, 0, 0);
Value of a variable $farewell is “now it’s time to say good bye”‘
Negative start
A negative value for start indicates the number of characters from the end of the string from which to start the replacement:
$farewell = substr_replace($farewell, “riddance”, -3);
Value of a variable $farewell is “now it’s time to say good riddance”
Negative length
A negative length indicates the number of characters from the end of the string at which to stop deleting:
$farewell = substr_replace($farewell, “”, -8, -5);
Value of a variable $farewell is “now it’s time to say good dance”