PHP str_replace() 函数

PHP 教程 · 2019-01-29 23:27:32

实例

把字符串 "Hello world!" 中的字符 "world" 替换成 "Peter":

<?php
echo str_replace("world","Peter","Hello world!");
?>

定义和用法

str_replace() 函数替换字符串中的一些字符(区分大小写)。

该函数必须遵循下列规则:

  • 如果搜索的字符串是一个数组,那么它将返回一个数组。
  • 如果搜索的字符串是一个数组,那么它将对数组中的每个元素进行查找和替换。
  • 如果同时需要对某个数组进行查找和替换,并且需要执行替换的元素少于查找到的元素的数量,那么多余的元素将用空字符串进行替换。
  • 如果是对一个数组进行查找,但只对一个字符串进行替换,那么替代字符串将对所有查找到的值起作用。

注释:该函数是区分大小写的。请使用 str_ireplace() 函数执行不区分大小写的搜索。

注释:该函数是二进制安全的。

语法


str_replace(find,replace,string,count)


参数 描述
find 必需。规定要查找的值。
replace 必需。规定替换 find 中的值的值。
string 必需。规定被搜索的字符串。
count 可选。一个变量,对替换数进行计数。

技术细节

返回值: 返回带有替换值的字符串或数组。
PHP 版本: 4+
更新日志: 在 PHP 5.0 中,新增了 count 参数。

在 PHP 4.3.3 之前,该函数的 findreplace 参数都为数组时将会遇到麻烦,会引起空的 find 索引在内部指针没有更换到 replace 数组上时被忽略。新的版本不会有这个问题。

自 PHP 4.0.5 起,大多数参数可以是一个数组。

更多实例

实例 1

使用带有数组和 count 变量的 str_replace() 函数:

<?php
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
echo "Replacements: $i";
?>

实例 2

使用带有需要替换的元素少于查找到的元素的 str_replace() 函数:

<?php
$find = array("Hello","world");
$replace = array("B");
$arr = array("Hello","world","!");
print_r(str_replace($find,$replace,$arr));
?>

点击查看所有 PHP 教程 文章: https://www.codercto.com/courses/l/5.html

查看所有标签

The Art of Computer Programming, Volumes 1-3 Boxed Set

The Art of Computer Programming, Volumes 1-3 Boxed Set

Donald E. Knuth / Addison-Wesley Professional / 1998-10-15 / USD 199.99

This multivolume work is widely recognized as the definitive description of classical computer science. The first three volumes have for decades been an invaluable resource in programming theory and p......一起来看看 《The Art of Computer Programming, Volumes 1-3 Boxed Set》 这本书的介绍吧!

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具