w3resource

PHP: substr_replace() function

Description

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

Version:

(PHP 4 and above)

Syntax:

substr_replace(string_name, replacement_string, start_pos, length) 

Parameters:

Name Description Required /
Optional
Type
string_name The input string. Required Mixed*
replacement_string The replacement string. Required String
start_pos Refers to the position of the string to start cutting -
A positive number : Start at the specified position from the string.
A negative number : Start at a specified position from the end of the string.
Required Integer
length Length of the replacing string.
A positive number : Start at the specified position from the string.
A negative number : Start at a specified position from the end of the string.
Optional Integer

Return value:

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

Value Type: Mixed.

*Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types.

Pictorial Presentation

string_substr_replace

Example:

<?php
$string1="Welcome to w3resource.com";
echo $string1;
echo '<br>';
echo substr_replace($string1,'NEW',0);
echo '<br>';
echo substr_replace($string1,'NEW',5);
echo '<br>';
echo substr_replace($string1,'NEW',0,0);
echo '<br>';
echo substr_replace($string1,'NEW',8,-2);
echo '<br>';
echo substr_replace($string1,'NEW',-6,-1);
echo '<br>';
echo substr_replace($string1,' ',1,-1);
?>

Output:

Welcome to w3resource.com
NEW
WelcoNEW
NEWWelcome to w3resource.com
Welcome NEWom
Welcome to w3resourNEWm
W m

View the example in the browser

See also

PHP Function Reference

Previous: substr_count
Next: substr



PHP: Tips of the Day

Deep flattens an array

Example:

<?php
function tips_deepFlatten($items)
{
  $result = [];
  foreach ($items as $item) {
    if (!is_array($item)) {
      $result[] = $item;
    } else {
      array_push($result, ...tips_deepFlatten($item));
    }
  }

  return $result;
}

Print_r(tips_deepFlatten([1, [2], [[3], 4], 5]));
?>

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)