PHP - Replacing a Portion of a String with substr_replace()

Introduction

substr_replace() replaces a specific portion of the target string.

To use it, pass three arguments:

  • the string to work on,
  • the replacement text, and
  • the index within the string at which to start the replacement.

substr_replace() replaces all the characters from the start point to the end of the string with the replacement text, returning the modified string as a copy.

The original string remains untouched.

Demo

<?php
$myString = "this is a test test test test test tttttttttt";

echo substr_replace( $myString, "T", 11 ) . " \n ";
?>/*www . j ava2  s.  c  om*/

Result

You can specify an optional fourth argument containing the number of characters to replace:

Demo

<?php
$myString = "this is a test test test test test tttttttttt,";

echo substr_replace( $myString, "T", 19, 5 ) . " \n ";
?>//  www .  java2 s . com

Result

Pass a negative fourth argument to replace up to that many characters from the end of the string:

Demo

<?php
$myString = "this is a test test test test test tttttttttt,";

echo substr_replace( $myString, "T", 19, -20 ) . " \n ";
?>//from   w  ww. jav a2s  . co m

Result

You can pass a zero value to insert the replacement text into the string rather than replacing characters:

Demo

<?php
$myString = "this is a test test test test test tttttttttt,";

echo substr_replace( $myString, "really ", 3, 0 ) . " \n ";
?>// w w  w.j  a v a 2 s .co m

Result

Related Topic