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 ";
?>//from   www  .j  av  a2s . co m

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 ";
?>/*from  ww  w  .ja  va  2s.c o  m*/

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 ww  w. j av a 2  s. c om*/

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 ";
?>/*from   ww  w.  ja v  a 2 s  .c  om*/

Result

Related Topic