Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

PHP แทนที่คำในประโยคด้วยสัญลักษณ์

ตัวอย่างโค้ด

<?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

พฤติกรรมรายละเอียด

SearchReplaceResult
"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