str_replace() Function

It 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 that 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.

Example: This example illustrate the basic implementation of the str_replace() Function in PHP.

PHP




<?php
   
// Input string
$subjectVal =
      "Computer Science in w3wiki is fun";
 
// Using str_replace() function
$resStr =
      str_replace('Science', 'algorithms', $subjectVal);
print_r($resStr);
?>


Output:

Computer algorithms in w3wiki is fun

Explain some string functions of PHP

In the programming world, a string is considered a data type, which in general is a sequence of multiple characters that can contain whitespaces, numbers, characters, and special symbols. For example, “Hello World!”, “ID-34#90” etc. PHP also allows single quotes(‘ ‘) for defining a string. Every programming language provides some in-built functions for the manipulation of strings. Some of the basic string functions provided by PHP are as follows:

Similar Reads

strlen() Function

It returns the length of the string i.e. the count of all the characters in the string including whitespace characters....

strrev() Function

...

trim(), ltrim(), rtrim(), and chop() Functions

It returns the reversed string of the given string....

strtoupper() and strtolower() Function

...

str_split() Function

It removes white spaces or other characters from the string. They have two parameters: one string and another charList, which is a list of characters that need to be omitted....

str_word_count() Function

...

strpos() Function

It returns the string after changing the cases of its letters....

str_replace() Function

...

ucwords() Function

It returns an array containing parts of the string....