ตัวอย่างโค้ด
<?php $my_str = "This is a sample only"; $search_str = ["sample", "This"]; $replace_str = ["simple"]; $result = str_replace($search_str, $replace_str, $my_str); echo "The final replaced string is: $result"; ?>
ผลลัพธ์
The final replaced string is: is a simple only
คำอธิบาย
str_replace($search, $replace, $subject)แทนที่ $search ด้วย $replace ใน $subject$search_strเป็น Array ["sample", "This"] - คำที่ต้องการแทนที่$replace_strเป็น Array ["simple"] - คำแทนที่ (สั้นกว่า Search Array)- เมื่อ Replace Array สั้นกว่า Search Array → Element ที่เกินจะถูกแทนที่ด้วย Empty String
พฤติกรรมรายละเอียด
| Search | Replace | Result |
|---|---|---|
| "sample" | "simple" | "simple" |
| "This" | (ไม่มี → Empty String) | "" (หายไป) |
ดังนั้น "This is a sample only" → " is a simple only" → Trim → "is a simple only"
วิธีอื่นๆ
preg_replace (Regex)
<?php
$str = "This is a sample only";
echo preg_replace('/\b(sample|This)\b/', 'simple', $str); // "is a simple only"
?>
strtr (Character/Substring Translation)
<?php $str = "This is a sample only"; echo strtr($str, ["sample" => "simple", "This" => ""]); // " is a simple only" ?>
substr_replace (Position-based)
<?php $str = "This is a sample only"; $pos = strpos($str, "sample"); echo substr_replace($str, "simple", $pos, 6); // "This is a simple only" ?>
Best Practice
- ใช้
str_replaceสำหรับ Simple Replacement (Fastest) - ใช้
preg_replaceเมื่อต้องการ Pattern/Regex - ใช้
strtrสำหรับ Character-level Translation - ระวัง Case Sensitivity - ใช้
str_ireplaceสำหรับ Case-insensitive