php Str_replace函数

时间:2010-12-15 13:53:25

标签: php urlencode

我有以下2个数组,我希望从中替换变量。但是我的问题是如何告诉不要替换%XX格式的变量。现在0将替换为%30,然后将再次替换为%%330(将3替换为%33)。非常感谢任何帮助。

$URL_Chars=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','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','0','1','2','3','4','5','6','7','8','9','-','.','_','~',':','/','?','#','[',']','@','!','$','&','\'','(',')','*','+',',',';','=','%');

$URL_Encoded_Chars=array('%41','%42','%43','%44','%45','%46','%47','%48','%49','%4A','%4B','%4C','%4D','%4E','%4F','%50','%51','%52','%53','%54','%55','%56','%57','%58','%59','%5A','%61','%62','%63','%64','%65','%66','%67','%68','%69','%6A','%6B','%6C','%6D','%6E','%6F','%70','%71','%72','%73','%74','%75','%76','%77','%78','%79','%7A','%30','%31','%32','%33','%34','%35','%36','%37','%38','%39','%2D','%2E','%5F','%7E','%3A','%2F','%3F','%23','%5B','%5D','%40','%21','%24','%26','%27','%28','%29','%2A','%2B','%2C','%3B','%3D','%25');

$Hex_URL=str_replace($URL_Chars,$URL_Encoded_Chars,$Hex_URL); 

3 个答案:

答案 0 :(得分:1)

你知道你可以使用e修饰符preg_replace以更干净的方式做到这一点:

echo preg_replace('/([A-Za-z0-9])/e', '"%".dechex(ord("\\1"))', 'Abc');
// outputs %41%62%63

如果你也想要其他角色,只需将它们添加到方括号[]中,当然可以在必要时将它们转义。

答案 1 :(得分:0)

解析字符串: 一次选择一个聊天,如果它等于'%',则以下字符为数字,忽略三个,否则替换当前的字符。

您可以使用1个assoziative数组设置replacemnt规则:

$replacements= array("A"=>"%41","B"=>"%42"....);

答案 2 :(得分:0)

我会这样做:

function myUrlencode($url) {
    $encodedUrl = '';

    foreach (str_split($url) as $char) {
        $encodedUrl .= '%'.dechex(ord($char));
    }

    return $encodedUrl;
}