Skip to content
Dec 29 / kkrizka

How To Insert A String Into Another String In PHP

Most programming languages have a function that allows you to insert one string into another string at a given position. For example, I can take the string blue and the string HI, and perform an operation blue.insert(HI,2) to get the resulatant string blHIue. But such a function does not come with the standard PHP library, at least not obviously. There is no function str_insert and a simple Google search does not bring any results. So one has to get creative and use the substr_replace function to insert a string into another by replacing a sub string of length 0 at the wanted position in the original.
The following is the arguments you should use to the substr_replace function if you want to insert one string into another string in PHP:
$newstring=substr_replace($orig_string, $insert_string, $position, 0);
Quite simple, no?


Leave a comment
  1. - / Dec 23 2009


  2. virtualTrader / Jan 6 2010

    Thanks, cool function!

  3. Litbea / Feb 21 2010

    Oh man, thanks a lot!

  4. Abdullah / Jul 18 2010

    Thanks for the time saving tip!

  5. cesconix / Nov 4 2010

    Good tip!

  6. TheTimeLord / Nov 16 2010

    Thx a lot for this tip :)

  7. Khaled / Dec 20 2010

    Thank you! :)

  8. Freeman / Jan 8 2011

    Hi Karol.

    This is interesting. I’m trying it out but it isn’t working. Can you enlighten me?

    I have a search filter for wordpress. It is replacing the ordinary tags url with a search on another domain – or should be!

    The search url is like so:

    So the $replace_with = ‘’;

    needs to be replaced with:

    then the $link followed by


    I tried using your example above but the search word always ends up in the very last position (at the end) of the string.

    Any ideas?


  9. Jafer Balti / Jun 23 2011

    Thanks karol nice tip

  10. dibi / Aug 24 2011

    great post..thanks dude..ur great..

  11. Savin / Aug 26 2011


  12. Victor / Oct 10 2011

    Thank you very much, very good

  13. Paul / Nov 23 2011

    Perfect :-)

    Thank you very much!

  14. moonpixel / Feb 13 2012

    Thanks mate, diky moc za jednoduche riesenie…

  15. Matthew Moore / Feb 18 2012

    Thanks for this!

  16. Nat / Aug 20 2012

    Thanks so much! Saved a lot of time! Keep up the good work!

Leave a comment