php实现替换
PHP实现字符串替换的方法
PHP提供了多种字符串替换函数,可根据不同需求选择合适的方法。
str_replace()函数 基本语法:
$new_string = str_replace($search, $replace, $subject);
示例:
$text = "Hello World";
$newText = str_replace("World", "PHP", $text);
// 结果:Hello PHP
str_ireplace()函数 不区分大小写的替换:

$text = "Hello world";
$newText = str_ireplace("WORLD", "PHP", $text);
// 结果:Hello PHP
substr_replace()函数 替换字符串的指定部分:
$text = "Hello World";
$newText = substr_replace($text, "PHP", 6, 5);
// 结果:Hello PHP
preg_replace()函数 使用正则表达式替换:

$text = "The price is $10.50";
$newText = preg_replace('/\$\d+\.\d{2}/', '$20.00', $text);
// 结果:The price is $20.00
数组替换功能
str_replace()支持数组参数:
$search = array("apple", "banana");
$replace = array("orange", "grape");
$text = "I like apple and banana";
$newText = str_replace($search, $replace, $text);
// 结果:I like orange and grape
回调函数替换
preg_replace_callback()允许使用回调函数:
$text = "Today is 2023-05-15";
$newText = preg_replace_callback(
'/(\d{4})-(\d{2})-(\d{2})/',
function($matches) {
return $matches[2].'/'.$matches[3].'/'.$matches[1];
},
$text
);
// 结果:Today is 05/15/2023
多字节字符串替换
对于多字节字符(如中文),使用mb_ereg_replace():
$text = "你好世界";
$newText = mb_ereg_replace("世界", "PHP", $text);
// 结果:你好PHP






