📜  php 替换字符串 - PHP (1)

📅  最后修改于: 2023-12-03 15:18:30.713000             🧑  作者: Mango

PHP 替换字符串

在 PHP 中,替换字符串是一项常见的任务。无论是替换文本中的某个单词,还是替换 URL 中的参数值,PHP 都提供了多种方法来完成这些任务。本文将介绍 PHP 中一些最常用的字符串替换函数。

str_replace()

str_replace() 函数用于在字符串中替换指定的文本。该函数接受三个参数:要查找的文本、要替换的文本和要替换的字符串。

$text = "The quick brown fox jumps over the lazy dog";
$newtext = str_replace("fox", "cat", $text);
echo $newtext;
// 输出:The quick brown cat jumps over the lazy dog
preg_replace()

preg_replace() 函数用于基于正则表达式在字符串中替换文本。该函数接受三个参数:一个正则表达式、要替换的文本和要替换的字符串。

$text = "The quick brown fox jumps over the lazy dog";
$newtext = preg_replace("/brown.*jumps/", "red dog", $text);
echo $newtext;
// 输出:The quick red dog over the lazy dog
strtr()

strtr() 函数用于在字符串中替换字符或一组字符。该函数接受两个参数:要替换的字符串和替换规则。替换规则可以是一个字符串或一个关联数组。

$text = "The quick brown fox jumps over the lazy dog";
$newtext = strtr($text, "abcedfghijklmnopqrstuvwxyz", "ABCD");
echo $newtext;
// 输出:ThE quick BrOwn fox jumps OvEr thE lAZY dOG
str_ireplace()

str_ireplace() 函数与 str_replace() 函数类似,但它是不区分大小写的。

$text = "The quick brown fox jumps over the lazy dog";
$newtext = str_ireplace("FOX", "cat", $text);
echo $newtext;
// 输出:The quick brown cat jumps over the lazy dog

以上是 PHP 中一些最常用的字符串替换函数。使用这些函数可以轻松地完成文本替换任务。