In this PHP tutorial, you shall learn how to insert a given character at specific index in the string using substr_replace() function, with example programs.
PHP – Insert character at specific index in string
To insert character at specific index in string in PHP, call substr_replace()
function and pass the given string, the character(as string), index/position at which we need to insert the character, and 0 as arguments.
Syntax
The syntax to insert a character ch
in a string str
at index/position pos
is
substr_replace($str, $ch, $pos, 0)
Examples
1. Insert char ‘m’ in string at position 3
In this example, we take a string in str
, char in ch
, position/index in pos
. We shall create a new string with the character ch
inserted in the string str
at index pos
.
PHP Program
<?php $str = 'apple'; $ch = 'm'; $pos = 3; $output = substr_replace($str, $ch, $pos, 0); echo $output; ?>
Output
Conclusion
In this PHP Tutorial, we learned how to insert a given character in a string at specific index/position, using substr_replace()
function, with the help of examples.