php实现替换
字符串替换函数
PHP提供了多个字符串替换函数,适用于不同场景:
str_replace() 是最基础的替换函数,支持数组替换:
$text = "Hello World";
$newText = str_replace("World", "PHP", $text); // 输出 "Hello PHP"
str_ireplace() 是不区分大小写的版本:

$text = "hello world";
$newText = str_ireplace("WORLD", "PHP", $text); // 输出 "hello PHP"
正则表达式替换
对于复杂模式匹配,使用 preg_replace():
$text = "2023-01-01";
$newText = preg_replace('/(\d{4})-(\d{2})-(\d{2})/', '$2/$3/$1', $text); // 输出 "01/01/2023"
数组批量替换
可以同时替换多个值:

$text = "apple banana cherry";
$search = ["apple", "banana"];
$replace = ["orange", "grape"];
$newText = str_replace($search, $replace, $text); // 输出 "orange grape cherry"
回调函数替换
使用 preg_replace_callback() 实现动态替换:
$text = "The price is {price}";
$newText = preg_replace_callback('/\{(\w+)\}/', function($matches) {
return strtoupper($matches[1]);
}, $text); // 输出 "The price is PRICE"
字符集处理
对于多字节字符,使用 mb_ereg_replace():
$text = "こんにちは";
$newText = mb_ereg_replace("こんにちは", "你好", $text); // 输出 "你好"
模板变量替换
实现模板引擎式的变量替换:
$vars = ['name' => 'John', 'age' => 30];
$template = "Name: {name}, Age: {age}";
$result = preg_replace_callback('/\{(\w+)\}/', function($m) use ($vars) {
return $vars[$m[1]] ?? $m[0];
}, $template); // 输出 "Name: John, Age: 30"






