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
echo str_replace("world","Peter","Hello world!");
?>
The output of the code above will be:
上述代码将输出下面的结果:
Example 2
案例2
In this example we will demonstrate str_replace() with an array and a count variable:
在下面的例子中,我们我们通过一个数组和一个count变量演示了str_ireplace()函数:
$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:
上述代码将输出下面的结果:
Example 3
案例3
In this example we will demonstrate str_replace() with less elements in replace than find:
在下面的例子中,我们演示了当使用str_replace()函数时,指定替代的元素少于搜索到的元素的情况:
$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:
上述代码将输出下面的结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)