The example in this article describes the insert substring method in the PHP string. Share to everyone for your reference, specific as follows:
Let's take a look at a common online approach:
Method One: 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);//output: 12345new_word67890
The above method uses the string traversal reorganization to implement the substring insertion function.
Let's look at an improved approach given by the cloud-dwelling community:
Method Two: Using SUBSTR function to intercept and combine
function Str_insert2 ($str, $i, $substr) {//Method two: substr function to intercept
$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 synthesized 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 the string and then assemble the string to realize the insertion effect of the substring.
Finally, the cloud-dwelling community offers one of the most direct ways:
Method Three: Inserting a substring directly using the Substr_replace function
Echo Substr_replace ($str, $sstr, 5,0);
Direct output here: 12345new_word67890
For more information about PHP interested readers can view the site topics: "PHP array Operation skills Encyclopedia", "PHP Data structure and algorithm tutorial", "PHP Mathematical Operation Skills Summary", "PHP date and Time usage summary", "PHP object-oriented Programming Program", " Summary of PHP string usage, Introduction to PHP+MYSQL database operations, and a summary of PHP common database operations Tips
I hope this article will help you with the PHP program design.