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.
You might also enjoy:
-
Today's little PHP hint is a pretty simple one, but one worth tackling if you are looking for a quick and easy way to strip a particular string pattern off ...
-
If you come from a VB programming background, often you are left floundering when trying to retrieve character codes from a string or vice versa, trying to ...
-
It is sometimes a good idea to obfuscate your query strings between web scripts, if only to prevent user URL tampering that could effect the outcome of your ...
-
I've written on the excellent jQuery Color Picker plugin from eyecon.ro before, but a question was recently raised on how to use its RGB output in code. Wel ...
-
Andrew Walker crafted this handy little PHP function which can convert a UTF-16 encoded string into a more PHP-friendly UTF-8 encoded string. The functio ...