php str_replace() 函数

本文详细介绍了PHP中的str_replace()函数的使用方法,包括其如何将一个字符串中的某些字符替换成另一些字符,遵循的规则及注意事项。并通过三个具体实例展示了不同情况下的应用。

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

 

 

转载于:https://www.cnblogs.com/qiantuwuliang/archive/2010/02/25/1673326.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值