PHP str_replace() Function with Example

PHP str_replace() Function: Here, we will find out about the str_replace() Function with Example in PHP.

PHP str_replace() Function

str_replace() work is utilized to supplant a given substring with determined substring in the string.

Syntax:

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

Here,

  • source_substring is the substring to be supplanted in the string.
  • target_substring is the substring to supplant with.
  • the string is the primary string where we need to supplant the substring.
  • tally is a discretionary parameter and it is utilized to store the absolute number of substitutions.

Example:

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

PHP Code:

<?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:

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

Leave a Comment

error: Alert: Content is protected!!