当前位置: 首页 > 网络学院 > 服务端脚本教程 > PHP > str_replace() 函数

PHP
PHP 介绍
PHP 安装
PHP 语法
PHP 变量
PHP操作符
PHP If...Else
PHP Switch
PHP 数组
PHP 循环
PHP 函数
PHP 表单
PHP $_GET
PHP $_POST
PHP Date
PHP Include
PHP 文件处理
PHP 文件上传
PHP Cookies
PHP Sessions
PHP 发送邮件

PHP 中的 str_replace() 函数


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-03-04   浏览: 467 ::
收藏到网摘: n/a

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_ireplace()函数时,指定替代的元素少于搜索到的元素的情况:

<?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] => !
)

评论 (0) All

登陆 | 还没注册?