urm*_*aul 522
$newstr = substr_replace($oldstr, $str_to_insert, $pos, 0);
Run Code Online (Sandbox Code Playgroud)
Tim*_*per 72
$str = substr($oldstr, 0, $pos) . $str_to_insert . substr($oldstr, $pos);
Run Code Online (Sandbox Code Playgroud)
ale*_*ets 10
尝试一下,它适用于任意数量的子串
<?php
$string = 'bcadef abcdef';
$substr = 'a';
$attachment = '+++';
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
?>
Run Code Online (Sandbox Code Playgroud)
小智 7
使用stringInsert函数而不是putinplace函数.我使用后来的函数来解析mysql查询.虽然输出看起来不错,但是查询导致了一个错误,我花了一些时间来追踪.以下是我的stringInsert函数版本,只需要一个参数.
function stringInsert($str,$insertstr,$pos)
{
$str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
return $str;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
这是我的简单解决方案,也就是在找到关键字后将文本附加到下一行。
$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!!!");
Run Code Online (Sandbox Code Playgroud)
输出:
This is a test
#FINDME#
Insert this awesome string below findme!!!
Other text and data.
Run Code Online (Sandbox Code Playgroud)