PHP Manual
Prev |  | Next

# substr_replace

substr_replace -- Replace text within a portion of a string.

## Description

`string substr_replace`(string string, string replacement, int start, int [length] );

substr_replace() replaces the part of `string` delimited by the `start` and (optionally) `length` parameters with the string given in `replacement`. The result is returned.

If `start` is positive, the replacing will begin at the `start`'th offset into `string`.

If `start` is negative, the replacing will begin at the `start`'th character from the end of `string`.

If `length` is given and is positive, it represents the length of the portion of `string` which is to be replaced. If it is negative, it represents the number of characters from the end of `string` at which to stop replacing. If it is not given, then it will default to strlen( `string` ); i.e. end the replacing at the end of `string`.

Example 1. Substr_replace() example
      1
      2 <?php
      3 $var = 'ABCDEFGH:/MNRPQR/';
      4 echo "Original: $var<hr>\n";
      5
      6 /* These two examples replace all of $var with 'bob'. */
      7 echo substr_replace ($var, 'bob', 0) . "<br>\n";
      8 echo substr_replace ($var, 'bob', 0, strlen ($var)) . "<br>\n";
      9
     10 /* Insert 'bob' right at the beginning of $var. */
     11 echo substr_replace ($var, 'bob', 0, 0) . "<br>\n";
     12
     13 /* These next two replace 'MNRPQR' in $var with 'bob'. */
     14 echo substr_replace ($var, 'bob', 10, -1) . "<br>\n";
     15 echo substr_replace ($var, 'bob', -7, -1) . "<br>\n";
     16
     17 /* Delete 'MNRPQR' from $var. */
     18 echo substr_replace ($var, '', 10, -1) . "<br>\n";
     19 ?>
     20

See also str_replace() and substr().

> Note: Substr_replace() was added in PHP 4.0.

Prev | Home | Next
substr | Up | trim