Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
PHP str_rot13() Function
Next article icon

PHP str_replace() Function

Last Updated : 30 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how to replace the occurrence of the search string with the replacing string using the str_replace() function in PHP, along with understanding their implementation through the examples.

The str_replace() is a built-in function in PHP and is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively. 

Syntax: 

str_replace ( $searchVal, $replaceVal, $subjectVal, $count )

Parameters: This function accepts 4 parameters out of which 3 are mandatory and 1 is optional. All of these parameters are described below: 

  • $searchVal: This parameter can be of both string and array types. This parameter specifies the string to be searched and replaced.
  • $replaceVal: This parameter can be of both string and array types. This parameter specifies the string with which we want to replace the $searchVal string.
  • $subjectVal: This parameter can be of both string and array types. This parameter specifies the string or array of strings which we want to search for $searchVal and replace with $replaceVal.
  • $count: This parameter is optional and if passed, its value will be set to the total number of replacement operations performed on the string $subjectVal.

Return Value: This function returns a string or an array based on the $subjectVal parameter with replaced values.

Approach: If the $searchVal and the $replaceVal arguments are arrays, then all the elements of the $searchVal argument are searched in the $subjectVal string and replaced by the corresponding elements in the $replaceVal argument. If a number of elements in $replaceVal are less than that in $searchVal array, then if there are any occurrences of the additional elements of $searchVal argument in the $subjectVal argument then they will be replaced by an empty string. If the $subjectVal parameter is also an array instead of a string then all of the elements of $subjectVal will be searched.

Consider the below example:  

Input:  $subjectVal  = "It was nice meeting you. May you shine brightly."         str_replace('you', 'him', $subjectVal) Output: It was nice meeting him. May him shine brightly. Explanation: Every occurrence of you is replaced with him.  Input:  $subjectVal  = "You eat fruits, vegetables, fiber every day."         $searchVal = array("fruits", "vegetables", "fiber")         $replaceVal = array("pizza", "beer", "ice cream")         str_replace($array1, $array2, $str) Output: You eat pizza, beer, ice cream every day. Explanation: Since both the arguments are arrays, therefore,  every element from the first argument is replaced with  the corresponding element from the second argument.

Example 1: The below example illustrate the str_replace() function in PHP.

PHP




<?php
 
  // Input string
  $subjectVal = "It was nice meeting you. May you shine bright.";
 
  // Using str_replace() function
  $resStr = str_replace('you', 'him', $subjectVal);
  print_r($resStr);
?>
 
 

Output:

It was nice meeting him. May him shine bright.

Example 2: This example describes replacing all the search strings with replacing strings using the str_replace() function.

PHP




<?php
 
  // Input string
  $str  = "You eat fruits, vegetables, fiber every day.";
 
  // Array containing search string
  $searchVal = array("fruits", "vegetables", "fiber");
 
  // Array containing replace string from  search string
  $replaceVal = array("pizza", "beer", "ice cream");
 
  // Function to replace string
  $res = str_replace($searchVal, $replaceVal, $str);
  print_r($res);
?>
 
 

Output:

You eat pizza, beer, ice cream every day.

Reference: http://php.net/manual/en/function.str-replace.php

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



Next Article
PHP str_rot13() Function

H

HGaur
Improve
Article Tags :
  • PHP
  • Web Technologies
  • PHP-function
  • PHP-string

Similar Reads

  • PHP addcslashes() Function
    The addcslashes() function is a built-in function in PHP. The addcslashes() function is used to add backslashes before some specified characters in a given string. Syntax: string addcslashes($string, $characters) Parameters: This function accepts two parameters as shown in the above syntax and are d
    2 min read
  • PHP addslashes() Function
    The addslashes() function is an inbuilt function in PHP and it returns a string with backslashes in front of predefined characters. It does not take any specified characters in the parameter. The predefined characters are: single quote (')double quote (")backslash (\)NULL Note: The addslashes() func
    2 min read
  • PHP bin2hex() Function
    The bin2hex() function in PHP converts a string to hexadecimal values. The conversion is done byte-wise with the high-nibble first. Note: It is not for converting strings representing binary digits into hexadecimal. Syntax: bin2hex($string) Parameters: This function accepts a single parameter $strin
    1 min read
  • PHP chop() Function
    The chop() in PHP is used to remove white spaces or any other specified characters from the end of a string. Syntax: string chop($string, $character) Parameters: This function accepts two parameters as shown in the above syntax and are described below: $string : It is used to specify the string whic
    2 min read
  • PHP chr() Function
    The chr() function is a built-in function in PHP and is used to convert a ASCII value to a character. It accepts an ASCII value as a parameter and returns a string representing a character from the specified ASCII value. The ASCII value can be specified in decimal, octal, or hex values. Octal values
    2 min read
  • PHP chunk_split() Function
    The chunk_split() function is a built-in function in PHP. The chunk_split() function is used to split a string into smaller chunks of a specific length. Syntax: string chunk_split($string, $length, $end) Parameters: This function accepts three parameters as shown in the above syntax and are describe
    2 min read
  • PHP convert_uudecode() Function
    The convert_uudecode() is a built in function in PHP. This function decode a uuencoded string encoded using convert_uuencode() function. The uudecode() functions makes string into printable form. Syntax: string convert_uudecode(string) Parameters: The uuencoded string which will be decoded. Return T
    1 min read
  • PHP convert_uuencode() Function
    The convert_uuencode() is a built-in function in PHP. The convert_uuencode() function encodes a string using the uuencode algorithm. Uuencode encoding translates all strings (including binary data) into printable characters which makes them safe for network transmissions. Syntax: String convert_uuen
    1 min read
  • PHP count_chars() Function
    The count_chars() is an inbuilt function in PHP and is used to perform several operations related to string like the number of an ASCII character occurs in a string. Syntax : count_chars(string,return_mode); Parameters: The count_chars() function takes two parameters string and return_mode as explai
    2 min read
  • PHP crc32() Function
    The crc32() function helps us to calculate a 32-bit crc or cyclic redundancy checksum polynomial for a string. The function uses the CRC32 algorithm.This function can be used to validate data integrity. However, to ensure that we get the correct string representation from the crc32() function, we ne
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences