Lau*_*ico 39 php arrays str-replace
str_replace使用数组时,我遇到了PHP函数的麻烦.
我有这样的信息:
$message = strtolower("L rzzo rwldd ty esp mtdsza'd szdepw ty esp opgtw'd dple");
Run Code Online (Sandbox Code Playgroud)
我试图这样使用str_replace:
$new_message = str_replace(
array('l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a','b','c','d','e','f','g','h','i','j','k'),
array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'),
$message);
Run Code Online (Sandbox Code Playgroud)
结果应该是A good glass in the bishop's hostel in the devil's seat,但相反,我得到了p voos vlpss xn twt qxswop's wosttl xn twt stvxl's stpt.
但是,当我只尝试更换2个字母时,它会很好地替换它们:
$new_message = str_replace(array('l','p'), array('a','e'), $message);
Run Code Online (Sandbox Code Playgroud)
字母l和p将被替换a和e.
如果它们的大小完全相同,为什么它不能使用完整的字母数组呢?
Rak*_*rne 50
因为str_replace()从左向右替换,所以在执行多次替换时,它可能会替换先前插入的值.
// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);
Ry-*_*Ry- 37
str_replace使用数组只是顺序执行所有替换.使用strtr,而不是做一次全部:
$new_message = strtr($message, 'lmnopq...', 'abcdef...');
Run Code Online (Sandbox Code Playgroud)
小智 16
简单而且比str_replace以下更好:
<?php
$arr = array(
"http://" => "http://www.",
"w" => "W",
"d" => "D");
$word = "http://desiweb.ir";
echo strtr($word,$arr);
?>
Run Code Online (Sandbox Code Playgroud)
strtrPHP doc 在这里