Insert Substring Method Summary in PHP string

Source: Internet
Author: User
This article mainly introduces the Insert Substring method in PHP string, compares and analyzes the string traversal, substr method interception and combination, and directly uses the Substr_replace function to insert three different implementations of substrings, involving the common techniques of PHP string manipulation, A friend you need can refer to the following

This example describes the insertion of a substring method in a PHP string. Share to everyone for your reference, as follows:

First 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 Scripting House:

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

The method uses the SUBSTR function to intercept the string, and then assemble the string to achieve the insertion effect of the substring.

The final script house provides you with one of the most straightforward methods:

Method Three: Inserting substrings directly using the Substr_replace function

Echo Substr_replace ($str, $sstr, 5,0);//Direct output here: 12345new_word67890

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.