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: