【问题标题】:How to handle an un-encoded special character in a url query string?如何处理 url 查询字符串中未编码的特殊字符?
【发布时间】:2017-03-31 03:54:09
【问题描述】:

我有一个这样的网址:

http://www.nearbynursinghomes.com/innerpage.php?state=CA&city=RIVERSIDE&shop=ALTA%20VISTA%20HEALTHCARE%20&%20WELLNESS%20CENTRE

我目前正在使用此代码:

$category = $_GET["state"];
$city= $_GET["city"];
$shop= $_GET["shop"];
if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; }; 

$start_from = ($page-1) * $results_per_page;
$sql = "SELECT *
    FROM $datatable 
    WHERE STATE='$category'
    AND CITY='$city'
    AND PROVNAME='$shop'
    ORDER BY PROVNAME ASC LIMIT $start_from, $results_per_page" ;
$rs_result = $conn->query($sql); 

但是它没有返回正确的值,因为值中间的& 表示shop=ALTA%20VISTA%20HEALTHCARE%20&%20WELLNESS%20CENTRE

它只是被切断了。我该如何解决这个问题?

【问题讨论】:

标签: php url get query-string url-encoding


【解决方案1】:

您的网址中有一个格式错误的查询字符串。你应该尽你所能从源头上纠正它。

如果您无法这样做,那么您可以采取最好的解决方法。

这不是一个特别有效的方法,也不是一个简单的模式 (Pattern Demo),但它适用于您的示例字符串。

您可以利用$_SERVER['REQUEST_URI'] 或任何您想捕获您的网址,然后使用此preg_match() 方法(PHP Demo):

$url=urldecode('http://www.nearbynursinghomes.com/innerpage.php?state=CA&city=RIVERSIDE&shop=ALTA%20VISTA%20HEALTHCARE%20&%20WELLNESS%20CENTRE');
if(preg_match_all('/(?<=[?&])([^=]+)=\K[^=]+(?=&|$)/',$url,$qs)){
    //              key------^^^^^^^   ^^^^^-------value
    $array=array_combine($qs[1],$qs[0]);
    var_export($array);
}

输出:

array (
  'state' => 'CA',
  'city' => 'RIVERSIDE',
  'shop' => 'ALTA VISTA HEALTHCARE & WELLNESS CENTRE',
)

然后,您可以在使用 placeholders 编写 MySQLi prepared statements 时引用这些数组元素。


如果您乐于使用 $_GET 访问其他键值对并且只想提取 shop 值,那么这是简单/直接的方法:

代码:(Demo)

$url = urldecode('http://www.nearbynursinghomes.com/innerpage.php?state=CA&city=RIVERSIDE&shop=ALTA%20VISTA%20HEALTHCARE%20&%20WELLNESS%20CENTRE&page=4');
echo preg_match('~[?&]shop=\K[^=]+(?=&|$)~', $url, $out) ? $out[0] : '[fail]';

输出:

ALTA VISTA HEALTHCARE & WELLNESS CENTRE

(Pattern Demo)

【讨论】:

  • @Charles 感谢您的支持。我已经扩展了我的答案以包含一个更简单的shop 特定解决方案。
【解决方案2】:

经过一夜好眠后,我使用此处提供的工具想出了这个解决方案。

$shop= $_SERVER['REQUEST_URI'];
$shop= explode("=", $shop,4);
$shop= $shop[3];
$shop= urldecode("$shop");

【讨论】:

    猜你喜欢
    • 2011-10-08
    • 2010-11-19
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2013-12-19
    相关资源
    最近更新 更多