In this tutorial, we will show you how to replace first and last character from string in PHP.
To Replace character from string PHP
Before we take an example of replace first and last character from string, Let’s see you substr_replace()
:
substr_replace() Function PHP
The PHP substr_replace() function is used to replace a part of a string with another string.
Here is 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().
Replace the first character from the string PHP
Suppose we have one string like this “Hello Developers”, In this string, we want to replace the first five characters in PHP. So you can use the substr_replace() function like this:
<?php $a_string = "Hello Developers"; echo "Given string: " . $string . "\n"; echo "Updated string: " . substr_replace($string, "Hi", 0, 5) . "\n"; ?>
We can now replace the first character with the new character using the str_replace()
function. The str_replace()
function takes three parameters: the string to search for, the string to replace with, and the string to search in. In our case, we want to search for the first character ($a_string
) and replace it with the new character (“Hi”).
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"; ?>
Finally, we can replace the last character with the new character using the str_replace()
function again.
And that’s it! We have successfully replaced the first and last characters of a string in PHP.
Recommended Posts:
To remove specific characters from string PHP
Conclusion
Replacing the first and last characters of a string in PHP is a simple task that can be accomplished using built-in PHP functions. By following the steps outlined in this article, you can easily modify a string to fit your needs.