Method to ignore case replacement: 1. Use str_ireplace() function, syntax "str_ireplace(search value, replacement value, string)"; 2. Use substr_replace() function, syntax "substr_replace(string) ,replacement value,start replacement position)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Method 1: Use The str_ireplace() function
replaces the character "WORLD" (case-insensitive) in the string "Hello world!" with "Shanghai":
<?php echo str_ireplace("WORLD","Shanghai","Hello world!"); ?>
Output :
Hello Shanghai!
Description:
str_ireplace() function replaces some characters in a string (not case-sensitive).
This function must follow the following rules:
If the searched string is an array, then it will return an array.
If the searched string is an array, then it will find and replace each element in the array.
If you need to search and replace the array at the same time, and the elements that need to be replaced are less than the number of found elements, the excess elements will be replaced with empty strings
If you search an array and replace only one string, the replacement string will work for all found values.
Syntax
str_ireplace(find,replace,string,count)
Parameters | Description |
---|---|
find | Required. Specifies the value to look for. |
replace | Required. Specifies a value that replaces the value in find. |
string | Required. Specifies the string to be searched for. |
count | Optional. A variable counting the number of substitutions. |
Method 2: Use the substr_replace() function
Replace "Hello" with "world":
<?php echo substr_replace("Hello","world",0); ?>
Output:
world
Description:
substr_replace() function replaces part of a string with another string.
substr_replace(string,replacement,start,length)
Parameters | Description |
---|---|
string | Required . Specifies the string to check. |
replacement | Required. Specifies the string to be inserted. |
start |
Required. Specifies where in the string to begin replacement.
|
length |
is optional. Specifies how many characters to replace. The default is the same as the string length.
|
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to replace strings in php ignoring case. For more information, please follow other related articles on the PHP Chinese website!