php method to add a string to a variable: first specify the string before the insertion position; then specify the string after the insertion position; finally put the string before the insertion position, three characters after the insertion position, to be inserted Join the strings together.
[Related learning recommendations: php graphic tutorial]
php method to add a string to a variable:
First look at the simple replacement:
$str1 = "*3*"; //原字符串 $str2 = "abc"; //要添加的字符串 $str1 = str_replace("3",$str2."3",$str1); //字符串替换 echo $str1;
is to replace 3 with abc3, But there is a premise for this: 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
Related learning recommendations:php programming(video)
The above is the detailed content of How to add string to variable in php. For more information, please follow other related articles on the PHP Chinese website!