有没有PHP函数可以做到这一点?
我使用strpos来获取子字符串的位置,我想在该位置之后插入一个字符串。
有没有PHP函数可以做到这一点?
我使用strpos来获取子字符串的位置,我想在该位置之后插入一个字符串。
当前回答
$newstr = substr_replace($oldstr, $str_to_insert, $pos, 0);
http://php.net/substr_replace
在上面的代码片段中,$pos用于函数的offset参数。
offsetIf偏移量非负,替换将从 偏移到字符串的偏移量。 如果偏移量为负,则替换将从偏移量开始 字符串末尾的字符。
其他回答
使用stringInsert函数,而不是putinplace函数。我使用后面的函数来解析mysql查询。虽然输出看起来不错,但查询导致了一个错误,我花了一段时间才找到。下面是只需要一个形参的stringInsert函数的版本。
function stringInsert($str,$insertstr,$pos)
{
$str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
return $str;
}
function insSubstr($str, $sub, $posStart, $posEnd){
return mb_substr($str, 0, $posStart) . $sub . mb_substr($str, $posEnd + 1);
}
试试吧,它对任意数量的子字符串都有效
<?php
$string = 'bcadef abcdef';
$substr = 'a';
$attachment = '+++';
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
?>
str_replace($sub_str, $insert_str.$sub_str, $org_str);
简单的另一种解决方法:
function stringInsert($str,$insertstr,$pos)
{
$count_str=strlen($str);
for($i=0;$i<$pos;$i++)
{
$new_str .= $str[$i];
}
$new_str .="$insertstr";
for($i=$pos;$i<$count_str;$i++)
{
$new_str .= $str[$i];
}
return $new_str;
}