PHP: Insert a String into another String

PHPWhile 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.

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code. Bookmark the permalink.
    blog comments powered by Disqus