【PHP】在目标字符串指定位置插入字符串

PHP如何在指定位置插入相关字符串,
例子:123456789变为1_23_456789
插入"_"到指定的位置!

(可以用作换行或者其他处理)

插入示例,具体思路在代码中有注释:

<?php
/**
 * 指定位置插入字符串
 * @param $str  原字符串
 * @param $i    插入位置
 * @param $substr 插入字符串
 * @return string 处理后的字符串
 */
function insertToStr($str, $i, $substr){
    //指定插入位置前的字符串
    $startstr="";
    for($j=0; $j<$i; $j++){
        $startstr .= $str[$j];
    }
    //指定插入位置后的字符串
    $laststr="";
    for ($j=$i; $j<strlen($str); $j++){
        $laststr .= $str[$j];
    }
    //将插入位置前,要插入的,插入位置后三个字符串拼接起来
    $str = $startstr . $substr . $laststr;
    //返回结果
    return $str;
}
 
//测试
$str="hello zhidao!";
$newStr=insertToStr($str, 6, "
");
echo $newStr;
//hello 
zhidao!
?>
原文地址:https://www.cnblogs.com/xuzhengzong/p/7754035.html