使用内置的 str_replace() 函数来替换字符串中的部分内容
2023-04-29 加入收藏
在 PHP 中,你可以使用内置的 str_replace() 函数来替换字符串中的部分内容。
例如,要将字符串中的所有空格替换为下划线,可以使用以下代码:
$str = "Hello, World!"; $str = str_replace(' ', '_', $str); // 将空格替换成下划线 echo $str; // 输出 Hello,_World!
你还可以使用 str_replace() 函数替换数组或多维数组中的字符串,例如:
$data = array( 'name' => 'John', 'age' => '30', 'address' => '123 Main St' ); // 将数组中的 "John" 替换成 "Jane" $data = str_replace('John', 'Jane', $data); print_r($data); // 将多维数组中的 "Main St" 替换成 "High St" $people = array( array('name' => 'John', 'address' => '123 Main St'), array('name' => 'Jane', 'address' => '456 Park Ave') ); function replace_address($item) { $item['address'] = str_replace('Main St', 'High St', $item['address']); return $item; } $people = array_map('replace_address', $people); print_r($people);
str_replace() 函数也支持将多个字符串替换成一个字符串,以及使用数组来替换字符串中的内容。