By substr_replace, I can insert a string in a specific index:
$a = 'abcdefg';
echo substr_replace($a, '1', 2, 0); // ab1cdefg
But, Is it possible to insert 2-3 strings at specific positions with just 1 substr_replace? (or other built-in functions)
for example:
$a = 'abcdefg';
$b = array('1', '2', '3');
$c = array(1, 2, 4);
echo substr_replace($a, $b, $c, 0); // a1b2cd3efg
I tried that code, but it returned an error:
Warning: substr_replace() [function.substr-replace]: ‘from’ and ‘len’
should be of same type – numerical or array
Thanks…
Now, first off, let me say that from reading the manual, I would have thought your code should work, you seem to be following the rules set out correctly.
What is even more ridiculous is that if you try and fix it by passing an array of
0s to$len(sounds reasonable based on that error message, no?) you get this:Right. So not only is the manual wrong, even the error messages contradict themselves. God I love PHP.
But enough of this, on to a solution…
Because it doesn’t work as expected, you will have to loop in order to do what you want. Not too hard, right? Well, the major tripping hazard here is that the length of the string and the offset positions will change on every iteration. In order to stop this from causing a problem, you will need to perform the replacements in reverse so that the indexes are where you expect them to be.
Something like this:
See it working