2014-11-03 88 views
2

如何將'&'符號添加到URL GET變量中,使其成爲字符串的一部分? 問題是它總是將字符串拆分爲下一個變量。

我該如何做這項工作?

localhost/test.php?variable='jeans&shirts' // so it executes it like a string 

<?php 

require "connect.php"; 

$variable = $_GET['variable']; 

echo $variable; 

?> 

輸出 '牛仔褲'

,而不是 '牛仔褲&襯衫'

回答

7

您將要urlencode()您的字符串:

// Your link would look like this: 
'localhost/test.php?variable='.urlencode('jeans&shirts'); 

當你想使用它,你會解碼它:

echo $variable = urldecode($_GET['variable']); 

ENCODE:http://php.net/manual/en/function.urlencode.php

DECODE:http://php.net/manual/en/function.urldecode.php


編輯:爲了測試這樣寫:

echo $url = 'localhost/test.php?variable='.urlencode('jeans&shirts'); 
echo '<br />'; 
echo urldecode($url); 

你的結果將是:

// Encoded 
localhost/test.php?variable=jeans%26shirts 
// Decoded 
localhost/test.php?variable=jeans&shirts 
+0

這是誤導。在URL中使用它之前,您需要對字符串進行urlencode編碼。你的第一行代碼根本不應該引用'$ _GET ['variable']',而是顯示一個鏈接標記或類似的代碼 – Steve 2014-11-03 19:10:44

+0

@Steve對不起,我在更新,因爲我知道這是有點誤導 – Rasclatt 2014-11-03 19:11:53

+0

不適用於我:\但不介意我通過排除URL中的'&'符號來解決問題 – 2014-11-03 19:12:11