title: PHP - How to replace special characters for url
body: <p>I am trying to convert special characters (eg. <code>+</code>, <code>/</code>, <code>&amp;</code>, <code>%</code>) which I will use them for a GET request. I have constructed a function for this.</p>
  
  <pre><code>function convert_text($text) {
  
      $t = $text;
  
      $specChars = array(
          ' ' =&gt; '%20',    '!' =&gt; '%21',    '"' =&gt; '%22',
          '#' =&gt; '%23',    '$' =&gt; '%24',    '%' =&gt; '%25',
          '&amp;' =&gt; '%26',    '\'' =&gt; '%27',   '(' =&gt; '%28',
          ')' =&gt; '%29',    '*' =&gt; '%2A',    '+' =&gt; '%2B',
          ',' =&gt; '%2C',    '-' =&gt; '%2D',    '.' =&gt; '%2E',
          '/' =&gt; '%2F',    ':' =&gt; '%3A',    ';' =&gt; '%3B',
          '&lt;' =&gt; '%3C',    '=' =&gt; '%3D',    '&gt;' =&gt; '%3E',
          '?' =&gt; '%3F',    '@' =&gt; '%40',    '[' =&gt; '%5B',
          '\\' =&gt; '%5C',   ']' =&gt; '%5D',    '^' =&gt; '%5E',
          '_' =&gt; '%5F',    '`' =&gt; '%60',    '{' =&gt; '%7B',
          '|' =&gt; '%7C',    '}' =&gt; '%7D',    '~' =&gt; '%7E',
      );
  
      foreach ($specChars as $k =&gt; $v) {
          $t = str_replace($k, $v, $t);
      }
  
      return $t;
  }
  </code></pre>
  
  <p>When I use <code>some text</code> as input for the function, I should get <code>some%20text</code>. But, because I do this replacement in a foreach loop, it first replaces 'space' to <code>%20</code> and in the second step it replaces <code>%</code> character to <code>%25</code>. Eventually I get <code>some%2520text</code>.</p>
  
  <p>Is there any other way or a built in function to make this substitution?</p>
  
  <p>rawurlencode replaces all the </p>
  
  <h3>EDIT</h3>
  
  <pre><code>$t = str_replace(array_keys($specChars), array_values($specChars), $text);
  </code></pre>
  
  <p>I have used str_replace without loop as <a href="https://stackoverflow.com/users/1441828/spongepablo">SpongePablo</a> suggested.</p>
  
  <p>It gives the same result which I do not desire. On the other hand, if I use <code>rawurlencode</code>, it converts some other characters which I don't want them to be converted.</p>