php Str_replace Function
I have the following 2 arrays that I am looking to replace variables from. However my problem is how to tell to not replace variables that are in %XX
format. Right now 0
will get replaced with %30
, and 开发者_运维知识库this will then again get replaced with %%330
(replaced 3
with %33
). Any help greatly appreciated.
$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);
You know you could do that in a cleaner fashion using preg_replace using the e
modifier:
echo preg_replace('/([A-Za-z0-9])/e', '"%".dechex(ord("\\1"))', 'Abc');
// outputs %41%62%63
If you want other characters too, just add them into the brackets []
, escaping them if necessary, of course.
Parse the string: Pick one chat at a time and if it equals '%' AND the following to chars are digits ignore rthose three, else replace the current char.
You can set your replacemnt rules with 1 assoziative array:
$replacements= array("A"=>"%41","B"=>"%42"....);
I would do it like this:
function myUrlencode($url) {
$encodedUrl = '';
foreach (str_split($url) as $char) {
$encodedUrl .= '%'.dechex(ord($char));
}
return $encodedUrl;
}
精彩评论