Insert string at specified position
$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.
$str = substr($oldstr, 0, $pos) . $str_to_insert . substr($oldstr, $pos);
substr
on PHP Manual
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;
}
This was my simple solution too append text to the next line after it found the keyword.
$oldstring = "This is a test\n#FINDME#\nOther text and data.";
function insert ($string, $keyword, $body) {
return substr_replace($string, PHP_EOL . $body, strpos($string, $keyword) + strlen($keyword), 0);
}
echo insert($oldstring, "#FINDME#", "Insert this awesome string below findme!!!");
Output:
This is a test
#FINDME#
Insert this awesome string below findme!!!
Other text and data.