PHP.nl

substr_replace

substr_replace

Replace text within a portion of a string

 **substr_replace**  $string  $replace  $offset  $length
replaces a copy of
delimited by the
and (optionally)
parameters with the string given in

. substr_replace``string``offset``length``replace

stringThe input string.

   An  of s can be provided, in which
   case the replacements will occur on each string in turn. In this case,
   the , 
   and  parameters may be provided either as
   scalar values to be applied to each input string in turn, or as
   s, in which case the corresponding array element will
   be used for each input string.
  `array``string``replace``offset``length``array`

replaceThe replacement string.

offset If is non-negative, the replacing will begin at the 'th offset into . offset``offset``string

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

length If given and is positive, it represents the length of the portion of which is to be replaced. If it is negative, it represents the number of characters from the end of at which to stop replacing. If it is not given, then it will default to strlen( ); i.e. end the replacing at the end of . Of course, if is zero then this function will have the effect of inserting into at the given offset. string``string``string``string``length``replace``string``offset

The result string is returned. If is an array then array is returned. string

Voorbeeld: Simple examples

<?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var<hr />\n";

/* These two examples replace all of $var with 'bob'. */
echo substr_replace($var, 'bob', 0) . "<br />\n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";

/* Insert 'bob' right at the beginning of $var. */
echo substr_replace($var, 'bob', 0, 0) . "<br />\n";

/* These next two replace 'MNRPQR' in $var with 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . "<br />\n";
echo substr_replace($var, 'bob', -7, -1) . "<br />\n";

/* Delete 'MNRPQR' from $var. */
echo substr_replace($var, '', 10, -1) . "<br />\n";
?>

**Voorbeeld: Using to replace multiple strings at once **

<?php
$input = array('A: XXX', 'B: XXX', 'C: XXX');

// A simple case: replace XXX in each string with YYY.
echo implode('; ', substr_replace($input, 'YYY', 3, 3))."\n";

// A more complicated case where each replacement is different.
$replace = array('AAA', 'BBB', 'CCC');
echo implode('; ', substr_replace($input, $replace, 3, 3))."\n";

// Replace a different number of characters each time.
$length = array(1, 2, 3);
echo implode('; ', substr_replace($input, $replace, 3, $length))."\n";
?>
A: YYY; B: YYY; C: YYY
A: AAA; B: BBB; C: CCC
A: AAAXX; B: BBBX; C: CCC

str_replace``substrString access and modification by character