PHP substr replace

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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 :

  1. $string1="Welcome to w3resource.com";  

  2. echo $string1;  

  3. echo '
    ';  

  4. echo substr_replace($string1,'NEW',0);  

  5. echo '
    ';  

  6. echo substr_replace($string1,'NEW',5);  

  7. echo '
    ';  

  8. echo substr_replace($string1,'NEW',0,0);  

  9. echo '
    ';  

  10. echo substr_replace($string1,'NEW',8,-2);  

  11. echo '
    ';  

  12. echo substr_replace($string1,'NEW',-6,-1);  

  13. echo '
    ';  

  14. echo substr_replace($string1,' ',1,-1);  

  15. ?>  

Output :

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