有没有PHP函数可以做到这一点?
我使用strpos来获取子字符串的位置,我想在该位置之后插入一个字符串。
有没有PHP函数可以做到这一点?
我使用strpos来获取子字符串的位置,我想在该位置之后插入一个字符串。
当前回答
这是我的简单解决方案,太追加文本到下一行后,它找到关键字。
$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!!!");
输出:
This is a test
#FINDME#
Insert this awesome string below findme!!!
Other text and data.
其他回答
function insSubstr($str, $sub, $posStart, $posEnd){
return mb_substr($str, 0, $posStart) . $sub . mb_substr($str, $posEnd + 1);
}
str_replace($sub_str, $insert_str.$sub_str, $org_str);
试试吧,它对任意数量的子字符串都有效
<?php
$string = 'bcadef abcdef';
$substr = 'a';
$attachment = '+++';
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
?>
这是我的简单解决方案,太追加文本到下一行后,它找到关键字。
$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!!!");
输出:
This is a test
#FINDME#
Insert this awesome string below findme!!!
Other text and data.
$str = substr($oldstr, 0, $pos) . $str_to_insert . substr($oldstr, $pos);
PHP手册中的substr