2013-12-13 67 views
1

我有一個生成一個散列並篩選出字符的功能:PHP快速輕鬆地替換字符?

$str = base64_encode(md5("mystring")); 
$str = str_replace("+", "_", 
      str_replace("/", "-", 
      str_replace("=", "x" $str 
     ))); 

什麼是「正確」的方式在PHP這樣做嗎?

即,有更清潔的方法嗎?

// Let "tr()" be an imaginary function 
$str = base64_encode(md5("mystring")); 
$str = tr( "+/=", "_-x", $str ); 
+0

固定。我們實際上使用md5,而不是base64_encode。 – redolent

回答

4

有一對夫婦選擇這裏,首先使用str_replace正確:

$str = str_replace(array('+', '/', '='), array('_', '-', 'x'), $str); 

還有的也總是被遺忘strtr

$str = strtr($str, '+/=', '_-x'); 
+0

完美!我不知道爲什麼我找不到這個功能。 – redolent

+0

的確,我總是忘記它。 –

1

您可以使用數組中str_replace函數這樣

$replace = Array('+', '/', '='); 
$with = Array('_', '-', 'x'); 
$str = str_replace($replace, $with, $str); 

希望它有幫助

1

您還可以使用strtr與數組。

strtr('replace :this value', array(
    ':this' => 'that' 
));