While most modern programming languages do feature a function that allows you to insert one string into another string at any given position, PHP for some or other reason simply doesn’t. So while you might be well versed in using a good old insert(str,x) function in any of the other languages that you might be used to, doing the same in PHP will no doubt leave you scratching your head as you frantically browse through all of the PHP string functions in their nifty online manual while trying to find the elusive little bugger.
So if no native string insert function exists, how exactly does one go about doing it then?
Well, the solution lies in the creative use of the PHP substring replace function (substr_replace). Essentially our goal is to insert our insert string into the original string by replacing a ‘substring’ of length zero at the desired position in the original string.
The syntax for doing this would then be:
$newstring = substr_replace($orig_string, $insert_string, $position, 0);
So for example if we wanted to inject ‘my’ into the classic sentence ‘Hello world!’, you would code:
echo substr_replace('Hello world!','my ',6,0);
Which would then result in ‘Hello my world!’ appearing on the screen. (Note, if you enter a negative position then the string is inserted so many characters from the end of the original string.)