Definition and Usage
定義和用法
The str_replace() function replaces some characters with some other characters in a string.
str_replace()函數的作用是:將某個子字串都替換為另一個字串(大小寫不敏感)。
This function works by the following rules:
這個函數必須遵循下列原則:
- If the string to be searched is an array, it returns an array
如果搜尋的字串是一個數組,那麼它將返回一個數組
- If the string to be searched is an array, find and replace is performed with every array element
如果搜尋的字串是一個數組,那麼它將對所有數組中的每個元素進行尋找和替換
- If both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace
如果同時需要對某個數組進行尋找和替換,並且需要執行替換的元素少於尋找到的元素的數量,那麼多餘的元素將用空值字串進行替換
- If find is an array and replace is a string, the replace string will be used for every find value
如果是對一個數組進行尋找,但只對一個字串進行替換,那麼“替代字串”將對所有尋找到的值起作用。
Syntax
文法
str_replace(find,replace,string,count) |
Parameter參數 |
Description描述 |
find |
Required. Specifies the value to find 必要參數。指定需要尋找的值 |
replace |
Required. Specifies the value to replace the value in find 必要參數。指定替代值 |
string |
Required. Specifies the string to be searched 必要參數。指定需要執行搜尋的字串 |
count |
Optional. A variable that counts the number of replacements 選擇性參數。指定需要執行替換的數量 |
Tips and Notes
注意點
Note: This function is case-sensitive. Use str_ireplace() to perform a case-insensitive search.
注意:str_replace()函數函數是區分大小寫。如果不需要對大小寫加以區分,那麼可以使用str_irreplace()函數,因為這個函數是不區分大小寫。
Note: This function is binary-safe.
注意:這個函數是“二進位精確的[binary-safe]”。
Example 1
案例1<?php
echo str_replace("world","Peter","Hello world!");
?>
The output of the code above will be:
上述代碼將輸出下面的結果:
Hello Peter!
Example 2
案例2
In this example we will demonstrate str_replace() with an array and a count variable:
在下面的例子中,我們我們通過一個數組和一個count變數示範了str_ireplace()函數:
<?php
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
echo "Replacements: $i";
?>
The output of the code above will be:
上述代碼將輸出下面的結果:
Array([0] => blue[1] => pink[2] => green[3] => yellow)Replacements: 1
Example 3
案例3
In this example we will demonstrate str_replace() with less elements in replace than find:
在下面的例子中,我們示範了當使用str_replace()函數時,指定替代的元素少於搜尋到的元素的情況:
<?php
$find = array("Hello","world");
$replace = array("B");
$arr = array("Hello","world","!");
print_r(str_replace($find,$replace,$arr));
?>
The output of the code above will be:
上述代碼將輸出下面的結果:
Array([0] => B[1] =>[2] => !)