Home » PHP

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.
Submitted by IncludeHelp, on February 05, 2019

PHP str_replace() Function

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

Syntax:

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

Here,

  • 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.

Examples:

    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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.