w3resource

PHP: substr_replace() function

PHP: Replace text within a portion of a string

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



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php/function-reference/substr_replace.php