insert a string into another string at a specific index in php

To insert a string into another string at a specific index in PHP, you can use string concatenation and the substr() function.

Here's an example of how to insert the string "world" into the string "hello" at index 5:

main.php
$originalString = "hello";
$stringToInsert = "world";
$index = 5;

$newString = substr($originalString, 0, $index) . $stringToInsert . substr($originalString, $index);
168 chars
6 lines

Explanation:

  • substr($originalString, 0, $index) gets the substring of the original string from the beginning up to the insertion index.
  • $stringToInsert is concatenated to the end of this substring.
  • substr($originalString, $index) gets the substring of the original string from the insertion index to the end.
  • The two substrings and $stringToInsert are concatenated together to create the new string.

The value of $newString in this example would be "helloworld".

gistlibby LogSnag