PHP str_replace() Function with Example

PHP str_replace() Function: Here, we are going to learn about the str_replace() Function with Example in PHP. By IncludeHelp Last updated : December 27, 2023

PHP str_replace() Function

The str_replace() function is used to replace a given substring with specified substring in the string.

Syntax

The syntax of the str_replace() function:

str_replace(source_substring, target_substring, string, [count]); 

Parameters

The parameters of the str_replace() function:

  • source_substring is the substring to be replaced in the string.
  • target_substring is the substring to replace with.
  • string is the main string in which we have to replace the substring.
  • count is an optional parameter and it is used to store the total number of replacements.

Return Value

The return value of this method is string, it returns a string or an array with all occurrences of search in subject replaced with the given replace value. [Source]

Sample Input/Output

Input:
str = "Hello guys, how are you?"
find = "Hello"
replace = "Hi"

Output: "Hi guys, how are you?"

Example of PHP str_replace() Function

<?php
$str = "Hello guys, how are you?";
$find = "Hello";
$replace = "Hi";
$target_str = str_replace($find, $replace, $str);
echo ($target_str . "\n");

$str = "Hello Hello this is Hello?";
$find = "Hello";
$replace = "Friends";
$target_str = str_replace($find, $replace, $str);
echo ($target_str . "\n");	
	
//below, we will count total number of replacements
$str = "Hello Hello this is Hello?";
$find = "Hello";
$replace = "Friends";
$count = 0;
$target_str = str_replace($find, $replace, $str, $count);
echo ($target_str . "\n");
echo ("Total replacements: $count \n");	
?>

Output

The output of the above example is:

Hi guys, how are you?
Friends Friends this is Friends?
Friends Friends this is Friends?
Total replacements: 3

To understand the above example, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.