PHP substr_replace() Function
In this chapter you will learn:
- Definition for PHP substr_replace() Function
- Syntax for PHP substr_replace() Function
- Parameter for PHP substr_replace() Function
- Return for PHP substr_replace() Function
- Example - Replace "Hello" with "world"
- Example - Start replacing at the 6th position in the string (replace "world" with "earth")
- Example - Start replacing at the 5th position from the end of the string (replace "world" with "earth")
- Example - Insert "Hello" at the beginning of "world"
- Example - Replace multiple strings at once. Replace "AAA" in each string with "BBB"
Definition
The substr_replace() function replaces one string with another string.
Syntax
PHP substr_replace() Function has the following syntax.
substr_replace(string,replacement,start,length)
Parameter
Parameter | Is Required | Description |
---|---|---|
string | Required. | String to check |
replacement | Required. | String to insert |
start | Required. | Where to start replacing in the string
|
length | Optional. | Specifies how many characters should be replaced.
|
Return
PHP substr_replace() Function returns the replaced string. If the string is an array then the array is returned.
Example 1
Replace "Hello" with "world":
<?php
echo substr_replace("Hello world from java2s.com","world",0);
?>
The code above generates the following result.
Example 2
Start replacing at the 6th position in the string (replace "world" with "earth"):
<?php
echo substr_replace("Hello world","earth",6);
?>
The code above generates the following result.
Example 3
Start replacing at the 5th position from the end of the string (replace "world" with "earth"):
<?php
echo substr_replace("Hello world","earth",-5);
?>
The code above generates the following result.
Example 4
Insert "Hello" at the beginning of "world":
<?php
echo substr_replace("world","Hello ",0,0);
?>
The code above generates the following result.
Example 5
Replace multiple strings at once. Replace "AAA" in each string with "BBB":
<?php
$replace = array("1: AAA","2: AAA","3: AAA");
echo implode("<br>",substr_replace($replace,'BBB',3,3));
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP trim() Function
- Syntax for PHP trim() Function
- Parameter for PHP trim() Function
- Return for PHP trim() Function
- Note for PHP trim() Function
- Example - Trim a string