In this PHP tutorial, you shall learn how to insert a substring at specific index in the string using substr_replace() function, with example programs.

PHP – Insert character at specific index in string

To insert a substring at specific index in a string in PHP, call substr_replace() function and pass the given string, the substring, index/position at which we need to insert the substring, and 0 as arguments.

Syntax

The syntax to insert a substring sub in a string str at index/position pos is

substr_replace($str, $sub, $pos, 0)
ADVERTISEMENT

Examples

1. Insert substring ‘abc’ in string at position 2

In this example, we take a string in str , substring in sub, position/index in pos. We shall create a new string with the substring sub inserted in the string str at index pos.

PHP Program

<?php
  $str = 'apple';
  $sub = 'abc';
  $pos = 2;
  $output = substr_replace($str, $sub, $pos, 0);
  echo 'Input  : ' . $str . '<br>'; 
  echo 'Output : ' . $output;
?>

Output

PHP - Insert character at specific index in string

Conclusion

In this PHP Tutorial, we learned how to insert a given substring in a string at specific index/position, using substr_replace() function, with the help of examples.