Insert string at specified position
Try it, it will work for any number of substrings
<?php
$string = 'bcadef abcdef';
$substr = 'a';
$attachment = '+++';
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
?>
Use the stringInsert function rather than the putinplace function. I was using the later function to parse a mysql query. Although the output looked alright, the query resulted in a error which took me a while to track down. The following is my version of the stringInsert function requiring only one parameter.
function stringInsert($str,$insertstr,$pos)
{
$str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
return $str;
}
$str = substr($oldstr, 0, $pos) . $str_to_insert . substr($oldstr, $pos);
substr
on PHP Manual
$newstr = substr_replace($oldstr, $str_to_insert, $pos, 0);
http://php.net/substr_replace
In the above snippet, $pos
is used in the offset
argument of the function.
offset
If offset is non-negative, the replacing will begin at the offset'th offset into string.If offset is negative, the replacing will begin at the offset'th character from the end of string.