High Efficiency of Array Replacement with str_replace in PHP

php str_replacearray replacementstring manipulationphp efficiencymultiple replacements
Published·Modified·

Previously, when writing PHP programs, I only knew how to use str_replace to replace a single word. If an article contained multiple keywords that needed replacement, I had to perform the replacement multiple times, which was very cumbersome. Later, I accidentally discovered that the parameters for str_replace can be arrays, allowing for the following syntax:

<?php
$str = "你今天开心不开心呀?";
$arr1 = array("你", "开心");
$arr2 = array("他", "快乐");
$str = str_replace($arr1, $arr2, $str);
echo $str;
?>

The final output is: "他今天快乐不快乐呀?". Isn't array replacement very convenient?