How to add a character to a specific position in a string in PHP
In this tutorial, we are going to learn how to add a character to a specific position in a string in PHP. We aim to insert a character or a substring in the given main string at the desired position. To achieve this we require the main string, a substring, and the position where the substring needs to be inserted.
PHP provides us a function named substr_replace() to insert any character or string in the main string.
Syntax: substr_replace(Main string, Substring, Position, Length)
Main string: The string in which we want to insert a character or a substring.
Substring: The string or the character which we want to add in the main string.
Position: The position at which the substring should be inserted. It is positive if we want to insert from the start of the string and it is negative if to insert from the end of the string.
Length: Length field indicates the length of the string we want to replace. This field should be 0 if we want to insert a substring instead of replacing it.
How To Insert a Substring into the Main String in PHP
Let’s observe an example:
Main string = “I love CodeSpeedy”
Sub string = “!”
Position = 17
Resultant string = “I love CodeSpeedy!”
Now the code for the same is
<?php $main_string = "I love CodeSpeedy"; $sub_string = '!'; $position = '17'; $result = substr_replace( $main_string, $sub_string, $position, 0 ); echo $result; ?>
I love CodeSpeedy!
The above code demonstrates the working of substr_replace function to insert a specified character “!” into the given main string “I love CodeSpeedy”. The function inserts ! into the main string at the 17th position of the main string. The resultant string will be “I love CodeSpeedy!”.
Thus, we have inserted a substring or a character into the main string.