mysql之URL Encode的实现

墨色 9月前 ⋅ 381 阅读

废话不多说,上代码了


CREATE FUNCTION urlencode(str VARCHAR(4096) CHARSET utf8) RETURNS varchar(4096) CHARSET utf8
BEGIN
  DECLARE sub VARCHAR(1) CHARSET utf8;
  DECLARE val BIGINT DEFAULT 0;
  DECLARE ind INT DEFAULT 1;
  DECLARE oct INT DEFAULT 0;
  DECLARE ret VARCHAR(4096) DEFAULT '';
  DECLARE octind INT DEFAULT 0;
  IF str is NULL THEN
      RETURN NULL;
  ELSE SET ret = '';
      WHILE ind <= CHAR_LENGTH(str) DO
        SET sub = MID(str, ind, 1);
        SET val = ORD(sub);
        IF NOT (val BETWEEN 48 AND 57 OR 
                val BETWEEN 65 AND 90 OR 
                val BETWEEN 97 AND 122 OR 
                val IN (45, 46, 95, 126)) THEN
            SET octind = OCTET_LENGTH(sub);
            WHILE octind > 0 DO
              SET oct = (val >> (8 * (octind - 1)));
              SET ret = CONCAT(ret, '%', LPAD(HEX(oct), 2, 0));
              SET val = (val & (POWER(256, (octind - 1)) - 1));
              SET octind = (octind - 1);
            END WHILE;
        ELSE
          SET ret = CONCAT(ret, sub);
        END IF;
        SET ind = (ind + 1);
    END WHILE;
  END IF;
  RETURN ret;
END


全部评论: 0

    我有话说: