PHP str_ireplace Function | Replace String with Another

PHP str_ireplace Function is an inbuilt function in PHP. It replaces all the occurrences of a string or an array of string in another string or an array of string respectively in a case-insensitive manner. In this article, we will discuss the PHP str_ireplace Function. Also, we will discuss a few examples of using it.

This function is similar to the PHP str_replace Function except str_replace is case-sensitive while str_ireplace is not.

Syntax

str_ireplace ( $search, $replace, $subject, $count )

Parameters

The PHP str_ireplace Function expects four parameters. However, only three parameters are mandatory and one is optional. The description of the parameters is as follows:

  • $search: The search parameter specifies the string to search. Also, it can be an array to specify multiple search strings.
  • $replace: The replace parameter specifies the string to replace with. Also, it can be an array to specify multiple replacements.
  • $subject: The subject string is the string or an array of string which will be searched and replaced on.
  • $count: The count parameter, if passed, is set to the total number of replacements done by the function. It is an optional parameter.

Points to Remember

Always remember the following points while working with str_ireplace function in PHP.

  1. If search and replace are arrays, then the function takes a value from each array and uses them to search and replace on the subject.
  2. Also, If replace has lesser values than search string, then the function assumes blank strings for the remaining values.
  3. If the search is an array and replace is a string, then the function searches for all values from search array and replaces the single string. However, the opposite is not true.
  4. If the subject is an array, then the function performs search and replace on every element of the array. Also, the return type of the function is also an array in this case.

Return Value

The PHP str_ireplace Function returns a string or an array of strings after replacing values. Also, it searches the string in a case-insensitive manner.

PHP str_ireplace Function

Example

<?php
	
	$search = 'world';
	$replace = 'There';
	$subject = 'Hello WORLD!';
	$finalString = str_ireplace($search, $replace, $subject);
	echo $finalString;

?>

In the above example, the str_replace function in PHP replaces all occurrences of ‘world’ with ‘There’ in the subject string. Also, do notice that the function performs the replace operation in case-insensitive manner.

OUTPUT:
Hello There!

For more detailed examples, you can refer to PHP str_replace Function.

Conclusion

In this article, we discussed the PHP str_ireplace Function. You can read more about it on the PHP Official Documentation. Additionally, you can read more about PHP String Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *