PHP - How to replace special characters for url

前端 未结 6 1156
囚心锁ツ
囚心锁ツ 2021-01-29 11:45

I am trying to convert special characters (eg. +, /, &, %) which I will use them for a GET request. I have constructed a

6条回答
  •  忘掉有多难
    2021-01-29 11:56

    There is a built-in PHP function for this, which is a far better option than doing it manually.

    urlencode - built in function from php

    However, if you still want to do it manually:

    function convert_text($text) {
    
    $t = $text;
    
    $specChars = array(
        '!' => '%21',    '"' => '%22',
        '#' => '%23',    '$' => '%24',    '%' => '%25',
        '&' => '%26',    '\'' => '%27',   '(' => '%28',
        ')' => '%29',    '*' => '%2A',    '+' => '%2B',
        ',' => '%2C',    '-' => '%2D',    '.' => '%2E',
        '/' => '%2F',    ':' => '%3A',    ';' => '%3B',
        '<' => '%3C',    '=' => '%3D',    '>' => '%3E',
        '?' => '%3F',    '@' => '%40',    '[' => '%5B',
        '\\' => '%5C',   ']' => '%5D',    '^' => '%5E',
        '_' => '%5F',    '`' => '%60',    '{' => '%7B',
        '|' => '%7C',    '}' => '%7D',    '~' => '%7E',
        ',' => '%E2%80%9A',  ' ' => '%20'
    );
    
    foreach ($specChars as $k => $v) {
        $t = str_replace($k, $v, $t);
    }
    
    return $t;
    }
    

    place the key and value in the last so that the last iteration of loop will be for spaces

提交回复
热议问题