substr_replace() function in PHP


The substr_replace() function is used to replace the part of string with another string.

Syntax

substr_replace(str,replacement,begin,len)

Parameters

  • str − The string to check

  • replacement − The string to insert

  • begin − The position from where the replacement begins −

    • If begin is a positive number: Begin replacing at the specified position in the string

    • If begin is a n number: - Begin replacing at the specified position from the end of the string

    • if begin is 0 - Begin replacing at the first character in the string.

  • len − The number of characters to be replaced. The default is the same length as the string.

    • If len is a positive number - The length of string to be replaced

    • If len is a negative number - How many characters should be left at end of string after replacing

    • If len is 0 - Insert instead of replace.

Return

The substr_replace() function returns the replaced string.

Example

The following is an example −

 Live Demo

<?php
   echo substr_replace("Demo text","word",5);
?>

Output

The following is the output −

Demo word

Example

Let us see another example to replace a string from the end of the string −

 Live Demo

<?php
   echo substr_replace("Demo text","word",-5);
?>

Output

The following is the output −

Demoword

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Dec-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements