Search code examples
phpstringhref

Variable passed into href only gives first word


I have this code:

$link ="<a href=http://www.gamingpopulace.com/threads/index?threadName='".$inputLocation."'>$inputLocation</a>";

$inputLocation= New Game Excitement

But only the first word of the variable is passed into $link, in this case "New". I know this is caused by not properly quoting the variable, but if I add any quotes around it now, an error is caused.
How do I pass all the words in the $inputLocation variable into the $link variable?
Thanks


Solution

  • You don't want to quote the variable, you want to URL-encode it. Something like this:

    $link = '<a href="http://www.gamingpopulace.com/threads/index?threadName=' . urlencode($inputLocation) . '">' . $inputLocation . '</a>';
    

    Note: This example also fixes a quoting issue you have where, while trying to quote the value, you weren't quoting the href attribute itself. In doing so I also swapped the usage of single-quotes and double-quotes since HTML attributes should be double-quoted.