您的位置:首页 > 编程语言 > PHP开发

php str_replace() 函数

2010-02-25 11:54 465 查看

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描述
findRequired. Specifies the value to find
必要参数。指定需要查找的值
replaceRequired. Specifies the value to replace the value in find
必要参数。指定替代值
stringRequired. Specifies the string to be searched
必要参数。指定需要执行搜索的字符串
countOptional. 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] => !)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: