How to add a string in php: first create an "insertToStr" method; then specify the string before the insertion position, and the string after the specified insertion position; then concatenate the three inserted strings; Finally output the result.
Recommended: "PHP Video Tutorial"
First look at the simple replacement:
$str1 = "*3*"; //原字符串 $str2 = "abc"; //要添加的字符串 $str1 = str_replace("3",$str2."3",$str1); //字符串替换 echo $str1;
That is to replace 3 with abc3, but there is a premise: you must know that there is a "3" in the original string before you can replace it, otherwise it cannot be replaced.
So you need to use another method at this time: add a string at the specified position, for example:
<?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, "baidu"); echo $newStr; //hello baiduzhidao! ?>
Test instructions: insert a new string at the 6th string position, And output the final result
The above is the detailed content of How to increase php string. For more information, please follow other related articles on the PHP Chinese website!