This article mainly introduces how to insert a substring into a PHP string, compares and analyzes the string traversal, and truncates and combines the substr method, the substr_replace function is used directly to insert sub-strings. it involves common php string operations, for more information about how to insert a substring into a PHP string, see the example in this article. We will share this with you for your reference. The details are as follows:
First, let's take a look at a common online method:
Method 1: string traversal
Function str_insert ($ str, $ I, $ substr) {for ($ j = 0; $ j <$ I; $ j ++) {$ startstr. = $ str [$ j];} for ($ j = $ I; $ j
The preceding method uses string traversal and reorganization to insert sub-strings.
Let's take a look at an improvement method provided by the script house:
Method 2: Use the substr function for truncation and combination
Function str_insert2 ($ str, $ I, $ substr) {// Method 2: Intercept the substr function $ start = substr ($ str, 0, $ I ); $ end = substr ($ str, $ I); $ str = ($ start. $ substr. $ end); return $ str; // return substr ($ str, 0, $ I ). $ substr. substr ($ str, $ I); // The above code can be combined into this sentence} $ str = "1234567890"; $ sstr = "new_word"; echo str_insert2 ($ str, 5, $ sstr); // output: 12345new_word67890
This method uses the substr function to intercept strings and then assemble strings to insert substrings.
Finally, I would like to provide you with the most direct method:
Method 3: Use the substr_replace function to insert a substring.
Echo substr_replace ($ str, $ sstr, 5, 0); // output directly here: 12345new_word67890