PHP str_replace() 字串取代
str_replace() 函數用來取代字串中的特定子字串。
基本用法
<?php
$str = "Hello World";
echo str_replace("World", "PHP", $str); // Hello PHP
echo str_replace("o", "0", $str); // Hell0 W0rld
?>
語法
str_replace(
array|string $search,
array|string $replace,
string|array $subject,
int &$count = null
): string|array
$search:要搜尋的值$replace:要替換的值$subject:要處理的字串或陣列$count:(可選)回傳取代的次數- 回傳值:取代後的字串或陣列
區分大小寫
str_replace() 區分大小寫:
<?php
$str = "Hello World";
echo str_replace("world", "PHP", $str); // Hello World(沒有取代)
echo str_replace("World", "PHP", $str); // Hello PHP
?>
str_ireplace() - 不區分大小寫
<?php
$str = "Hello World";
echo str_ireplace("WORLD", "PHP", $str); // Hello PHP
echo str_ireplace("hello", "Hi", $str); // Hi World
?>
陣列取代
搜尋和取代都是陣列
<?php
$str = "The quick brown fox";
$search = ["quick", "brown", "fox"];
$replace = ["slow", "white", "dog"];
echo str_replace($search, $replace, $str);
// The slow white dog
?>
對應關係
<?php
$str = "1 2 3";
$search = ["1", "2", "3"];
$replace = ["one", "two", "three"];
echo str_replace($search, $replace, $str);
// one two three
?>
取代陣列比搜尋陣列短
<?php
$str = "a b c d";
$search = ["a", "b", "c", "d"];
$replace = ["1", "2"]; // 只有兩個
echo str_replace($search, $replace, $str);
// 1 2 (c 和 d 被替換成空字串)
?>
用單一值取代多個
<?php
$str = "a, b, c, d";
$search = [", ", ","];
$replace = "-";
echo str_replace($search, $replace, $str);
// a-b-c-d
?>
處理陣列主體
<?php
$subjects = [
"Hello World",
"Hello PHP",
"Hello Everyone"
];
$result = str_replace("Hello", "Hi", $subjects);
print_r($result);
// ["Hi World", "Hi PHP", "Hi Everyone"]
?>
取得取代次數
<?php
$str = "Hello Hello Hello";
$count = 0;
$result = str_replace("Hello", "Hi", $str, $count);
echo $result; // Hi Hi Hi
echo $count; // 3
?>
鏈式取代注意事項
<?php
$str = "a";
// 鏈式取代可能產生意外結果
$search = ["a", "b"];
$replace = ["b", "c"];
echo str_replace($search, $replace, $str);
// c(不是 b!因為 a→b,然後 b→c)
// 如果需要同時取代,考慮使用 strtr()
echo strtr($str, ["a" => "b", "b" => "c"]);
// b
?>
strtr() - 同時取代
<?php
$str = "ab";
// str_replace 是依序取代
echo str_replace(["a", "b"], ["b", "a"], $str);
// aa(a→b,然後 b→a,全變成 a)
// strtr 是同時取代
echo strtr($str, ["a" => "b", "b" => "a"]);
// ba(正確交換)
?>
常見應用
移除字元
<?php
$str = "Hello World";
// 移除空格
echo str_replace(" ", "", $str); // HelloWorld
// 移除多種字元
echo str_replace([" ", "!", "?"], "", "Hello! World?"); // HelloWorld
?>
格式化資料
<?php
// 清理電話號碼
function cleanPhone(string $phone): string {
return str_replace(["-", " ", "(", ")"], "", $phone);
}
echo cleanPhone("(02) 1234-5678"); // 0212345678
// 格式化貨幣顯示
function formatCurrency(string $amount): string {
return str_replace(",", "", $amount); // 移除千位分隔符
}
echo formatCurrency("1,234,567"); // 1234567
?>
HTML 實體轉換
<?php
$str = "5 > 3 && 2 < 4";
// 簡單的 HTML 跳脫
$html = str_replace(
["&", "<", ">", '"', "'"],
["&", "<", ">", """, "'"],
$str
);
echo $html; // 5 > 3 && 2 < 4
// 實際上應該使用 htmlspecialchars()
echo htmlspecialchars($str);
?>
模板變數替換
<?php
$template = "Dear {{name}}, your order #{{order_id}} is confirmed.";
$data = [
"{{name}}" => "Alice",
"{{order_id}}" => "12345"
];
$message = str_replace(
array_keys($data),
array_values($data),
$template
);
echo $message;
// Dear Alice, your order #12345 is confirmed.
?>
清理使用者輸入
<?php
function sanitize(string $input): string {
// 移除可能有害的字元
$dangerous = ["<script>", "</script>", "javascript:", "onclick="];
return str_ireplace($dangerous, "", $input);
}
$input = "<script>alert('XSS')</script>";
echo sanitize($input); // alert('XSS')
// 實際上應該使用 htmlspecialchars() 或更完整的清理方式
?>
URL Slug 生成
<?php
function slugify(string $text): string {
// 轉小寫
$text = strtolower($text);
// 替換空格和特殊字元
$text = str_replace([" ", "_", "&"], "-", $text);
// 移除其他特殊字元
$text = preg_replace('/[^a-z0-9\-]/', '', $text);
// 移除重複的連字號
$text = preg_replace('/-+/', '-', $text);
return trim($text, '-');
}
echo slugify("Hello World & PHP!"); // hello-world-php
?>
效能考量
<?php
// 多個 str_replace 呼叫
$str = "...";
$str = str_replace("a", "1", $str);
$str = str_replace("b", "2", $str);
$str = str_replace("c", "3", $str);
// 合併成一次呼叫更有效率
$str = str_replace(["a", "b", "c"], ["1", "2", "3"], $str);
?>
與其他函數比較
| 函數 | 說明 |
|---|---|
str_replace() | 取代子字串(區分大小寫) |
str_ireplace() | 取代子字串(不區分大小寫) |
strtr() | 同時取代多個字元或子字串 |
preg_replace() | 使用正規表示式取代 |
substr_replace() | 取代指定位置的子字串 |