Search code examples
phpjavascriptregexgethref

sanitize string for use in href with PHP GET


I am trying to add a user-defined string to information passed to a third party via href. So I have something that will look like

<a href="http://thirdparty.com/?data_set=USERSTRING" target="_blank">Link Text</a>

USERSTRING is known when the page loads so it could be put in the href by php when the page loads, or I can dynamically add it with javascript.

What I don't know is what I need to do to escape any special characters so that the link works and can be read on the other end - USERSTRING could be something really annoying like: [He said, "90% isn't good enough?"] The data is only used in an auto-generated file name so it doesn't need to be preserved 100%, but I'm trying to avoid gratuitous ugliness.


Solution

  • The urlencode() function provides exactly what you are looking for, ie:

    <a href="http://thirdparty.com/?data_set=<?php echo urlencode('USERSTRING'); ?>" target="_blank">Link Text</a>