php向字符串的指定位置插入另一个字符串

时间:2017-07-27
本文章向大家介绍php向一个字符串的指定位置插入另外一个字符串,需要的朋友可以参考一下。

我使用strpos获取字符串的位置,我想在该位置之后插入例外一个字符串。有没有PHP函数可以做到这一点?

第一种方法:使用substr_replace

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

第二种方法:使用str_replace

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

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

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

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

第三种方法:使用substr

function stringInsert($str,$insertstr,$pos)
{
    $str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
    return $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;

}