有没有PHP函数可以做到这一点?

我使用strpos来获取子字符串的位置,我想在该位置之后插入一个字符串。


当前回答

奇怪的答案!您可以使用sprintf[文档链接]轻松地将字符串插入到其他字符串中。这个函数非常强大,可以处理多个元素和其他数据类型。

$color = 'green';
sprintf('I like %s apples.', $color);

给你字符串

I like green apples.

其他回答

$newstr = substr_replace($oldstr, $str_to_insert, $pos, 0);

http://php.net/substr_replace

在上面的代码片段中,$pos用于函数的offset参数。

offsetIf偏移量非负,替换将从 偏移到字符串的偏移量。 如果偏移量为负,则替换将从偏移量开始 字符串末尾的字符。

function insSubstr($str, $sub, $posStart, $posEnd){
  return mb_substr($str, 0, $posStart) . $sub . mb_substr($str, $posEnd + 1);
}
$str = substr($oldstr, 0, $pos) . $str_to_insert . substr($oldstr, $pos);

PHP手册中的substr

试试吧,它对任意数量的子字符串都有效

<?php
    $string = 'bcadef abcdef';
    $substr = 'a';
    $attachment = '+++';

    //$position = strpos($string, 'a');

    $newstring = str_replace($substr, $substr.$attachment, $string);

    // bca+++def a+++bcdef
?>

奇怪的答案!您可以使用sprintf[文档链接]轻松地将字符串插入到其他字符串中。这个函数非常强大,可以处理多个元素和其他数据类型。

$color = 'green';
sprintf('I like %s apples.', $color);

给你字符串

I like green apples.