Replace First and Last Character From String PHP

To replace the first and last character from a string PHP.
Sometime, we need to replace first or last characters from strings in PHP. This tutorial shows you PHP functions that help to replace first and last character from string.
We can use the substr_replace function in PHP to replace first or last character from string in PHP.
To Replace character from string PHP
Before we take an example to replace first character from string and replace last character from a string. We will explain you substr_replace() in PHP.
substr_replace() Function PHP
The PHP substr_replace() function is used to replace a part of a string with another string.
Syntax
substr_replace($str, $replacement, $start, $length)
Parameters
The substr_replace() function is accept only 4 parameters. And the first three parameters are required and remember the last parameter is optional. Below we have described all parameters of substr_replace().
- $str: This parameter is required. In this parameter, we will put original string.
- $replacement: This parameter is also required. In this parameter, we will put other string we want to replace with the original string.
- $start: This parameter is also required.
- When we put a positive number in $start, replacement starts at the specified position in the string.
- When we put a negative number in $start, replacement starts at the specified position from the end of the string.
- If $start is 0, replacement occurs from the first character of the string.
- $length: It’s last parameter and optional.
- If $ length is positive, it represents the length of the part of the $ string that is to be replaced.
- If $ length is negative, it represents the number of characters before the end of the $ string from which the first substitution needs to be stopped.
- If $ length is 0, then insertion is done instead of substitution.
Replace first character from string PHP
Suppose we have one string like this “Hello Developers”. In this string we want to replace first five characters in PHP. So you can use the substr_replace() function like this:
<?php $string = "Hello Developers"; echo "Given string: " . $string . "\n"; echo "Updated string: " . substr_replace($string, "Hi", 0, 5) . "\n"; ?>
Replace last character from string PHP
Suppose we have one string like this “Hello World” . In this string we want to replace last five characters in PHP. So you can use the substr_replace() function like this:
<?php $string = "Hello World"; echo "Given string: " . $string . "\n"; echo "Updated string: " . substr_replace($string ,"dev",-5) . "\n"; ?>
Conclusion
How to replace first and last character from a string. In this tutorial, we have learned how to replace first and last character from any given strings.