Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Chương trình PHP thay thế từ bằng ký hiệu khác trong câu

Ví dụ

<?php
$my_str = "This is a sample only";
$search_str = array("sample", "This");
$replace_str = array("simple");
$result = str_replace($search_str, $replace_str, $my_str);
print_r("The final replaced string is: ");
print_r($result);
?>

Kết quả

The final replaced string is: is a simple only

Giải thích

Chuỗi gốc, mảng từ cần tìm, mảng từ thay thế:

$my_str = "This is a sample only";
$search_str = array("sample", "This");
$replace_str = array("simple");

str_replace() thay thế giá trị tìm thấy bằng giá trị mới. Kết quả in ra:

$result = str_replace($search_str, $replace_str, $my_str);
print_r("The final replaced string is: ");
print_r($result);

Lưu ý: $search_str có 2 phần tử nhưng $replace_str chỉ 1. str_replace sẽ dùng cùng "simple" cho cả "sample" và "This". Kết quả: "This" -> "simple", "sample" -> "simple" => "simple is a simple only". Output ví dụ gốc có vẻ bị thiếu "simple" đầu tiên.