有没有PHP函数可以做到这一点?
我使用strpos来获取子字符串的位置,我想在该位置之后插入一个字符串。
有没有PHP函数可以做到这一点?
我使用strpos来获取子字符串的位置,我想在该位置之后插入一个字符串。
当前回答
试试吧,它对任意数量的子字符串都有效
<?php
$string = 'bcadef abcdef';
$substr = 'a';
$attachment = '+++';
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
?>
其他回答
$str = substr($oldstr, 0, $pos) . $str_to_insert . substr($oldstr, $pos);
PHP手册中的substr
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
?>
$newstr = substr_replace($oldstr, $str_to_insert, $pos, 0);
http://php.net/substr_replace
在上面的代码片段中,$pos用于函数的offset参数。
offsetIf偏移量非负,替换将从 偏移到字符串的偏移量。 如果偏移量为负,则替换将从偏移量开始 字符串末尾的字符。
只是想添加一些东西:我发现tim cooper的答案非常有用,我用它来做一个方法,它接受一个位置数组,并对所有它们进行插入,所以这里是:
编辑:看起来我的旧函数假设$insertstr只有1个字符,并且数组已排序。这适用于任意长度的字符。
function stringInsert($str, $pos, $insertstr) {
if (!is_array($pos)) {
$pos = array($pos);
} else {
asort($pos);
}
$insertionLength = strlen($insertstr);
$offset = 0;
foreach ($pos as $p) {
$str = substr($str, 0, $p + $offset) . $insertstr . substr($str, $p + $offset);
$offset += $insertionLength;
}
return $str;
}