Current Location: Home> Function Categories> substr_replace

substr_replace

Substrings that replace strings
Name:substr_replace
Category:String
Programming Language:php
One-line Description:Replace part of the string with another string.

Definition and usage

substr_replace() function replaces part of the string with another string.

Note: If the start parameter is a negative number and length is less than or equal to start , then length is 0.

Note: This function is binary safe.

Example

Example 1

Replace "Hello" with "world":

 <?php
echo substr_replace ( "Hello" , "world" , 0 ) ;
?>

Try it yourself

Example 2

Replace from the 6th position of the string (replace "world" with "Shanghai"):

 <?php
echo substr_replace ( "Hello world" , "Shanghai" , 6 ) ;
?>

Try it yourself

Example 3

Replace from the 5th position at the end of the string (replace "world" with "Shanghai"):

 <?php
echo substr_replace ( "Hello world" , "Shanghai" , - 5 ) ;
?>

Try it yourself

Example 4

Insert "Hello" at the beginning of "world":

 <?php
echo substr_replace ( "world" , "Hello " , 0 , 0 ) ;
?>

Try it yourself

Example 5

Replace multiple strings at once. Replace "AAA" in each string with "BBB":

 <?php
$replace = array ( "1: AAA" , "2: AAA" , "3: AAA" ) ;
echo implode ( "<br>" , substr_replace ( $replace , 'BBB' , 3 , 3 ) ) ;
?>

Try it yourself

grammar

 substr_replace ( string , replacement , start , length )
parameter describe
string Required. Specifies the string to be checked.
replacement Required. Specifies the string to be inserted.
start

Required. Specifies where to start the replacement of the string.

  • Positive number - Start replacing at the specified position in the string
  • Negative number - Replace at the specified position at the end of the string
  • 0 - Start replacing at the first character in the string
length

Optional. Specify how many characters to replace. The default is the same length as the string.

  • Positive number - replaced string length
  • Negative number - represents the number of characters at the end of the substring to be replaced from the end of the string .
  • 0 - Insert rather than replace
Similar Functions
Popular Articles