php实现替换
字符串替换
使用 str_replace() 函数可以替换字符串中的特定内容。该函数接受三个参数:查找的字符串、替换的字符串以及被搜索的字符串。
$original = "Hello World";
$replaced = str_replace("World", "PHP", $original);
echo $replaced; // 输出 "Hello PHP"
数组替换
str_replace() 也支持数组替换,可以同时替换多个值。第一个参数和第二个参数可以是数组,表示多组查找和替换。
$original = "apple, banana, cherry";
$find = ["apple", "banana"];
$replace = ["orange", "grape"];
$replaced = str_replace($find, $replace, $original);
echo $replaced; // 输出 "orange, grape, cherry"
正则表达式替换
使用 preg_replace() 函数可以进行基于正则表达式的替换。该函数接受正则表达式模式、替换字符串以及被搜索的字符串。

$original = "The year is 2023";
$replaced = preg_replace("/\d+/", "2024", $original);
echo $replaced; // 输出 "The year is 2024"
多模式替换
preg_replace() 支持多模式替换,可以传入模式数组和替换数组。
$original = "123 abc 456";
$patterns = ["/\d+/", "/[a-z]+/"];
$replacements = ["number", "letters"];
$replaced = preg_replace($patterns, $replacements, $original);
echo $replaced; // 输出 "number letters number"
回调函数替换
preg_replace_callback() 允许使用回调函数动态生成替换内容。回调函数接收匹配数组并返回替换字符串。

$original = "3 apples and 5 oranges";
$replaced = preg_replace_callback("/\d+/", function($matches) {
return $matches[0] * 2;
}, $original);
echo $replaced; // 输出 "6 apples and 10 oranges"
不区分大小写替换
str_ireplace() 是 str_replace() 的不区分大小写版本,用法相同但忽略大小写差异。
$original = "Hello WORLD";
$replaced = str_ireplace("world", "PHP", $original);
echo $replaced; // 输出 "Hello PHP"
子字符串替换
substr_replace() 可以在指定位置替换子字符串。参数包括原字符串、替换字符串、起始位置和替换长度。
$original = "Hello World";
$replaced = substr_replace($original, "PHP", 6, 5);
echo $replaced; // 输出 "Hello PHP"
字符转换
strtr() 函数可以按字符或字符串映射表进行替换。接受字符串和替换映射数组。
$original = "abcde";
$trans = ["a" => "1", "b" => "2"];
$replaced = strtr($original, $trans);
echo $replaced; // 输出 "12cde"






