The example in this article describes the method of inserting substrings into PHP strings. Share it with everyone for your reference, the details are as follows:
First, let’s take a look at a common method on the Internet:
Method 1: String traversal
function str_insert($str, $i, $substr) { for($j=0; $j<$i; $j++){ $startstr .= $str[$j]; } for ($j=$i; $j<strlen($str); $j++){ $laststr .= $str[$j]; } $str = ($startstr . $substr . $laststr); return $str; } $str="1234567890"; $sstr="new_word"; echo str_insert($str,5,$sstr);//输出:12345new_word67890
The above method uses string traversal and reorganization to achieve the insertion of substrings Function.
Let’s take a look at an improvement method given by this site:
Method 2: Use the substr function to intercept and combine
function str_insert2($str,$i,$substr){//方法二:substr函数进行截取 $start=substr($str,0,$i); $end=substr($str,$i); $str = ($start . $substr . $end); return $str; //return substr($str,0,$i).$substr.substr($str,$i);//上述代码可综合成这一句 } $str="1234567890"; $sstr="new_word"; echo str_insert2($str,5,$sstr);//输出:12345new_word67890
This method directly uses the substr function to intercept the string, and then assemble the string. This achieves the insertion effect of substrings.
Finally, this site provides you with the most direct method:
Method 3: Directly use the substr_replace function to insert substrings
echo substr_replace($str,$sstr,5,0); //此处直接输出:12345new_word67890
Readers who are interested in more PHP-related content can check out the special topics of this site: "Complete PHP array (Array) operation skills", "PHP data structure and algorithm tutorial", "PHP mathematical operation skills summary", "php date and time usage summary", "php object-oriented programming introductory tutorial", "php characters" "Summary of String Usage", "Introduction Tutorial on PHP+MySQL Database Operation" and "Summary of Common PHP Database Operation Skills"
I hope this article will be helpful to everyone in PHP programming.
The above is a summary of the method of inserting substrings into PHP strings. It is original, including strings and PHP content. I hope it will be helpful to friends who are interested in PHP tutorials.