我使用 Get 函数在 url 中查找字段 model
但当模型包含空格和连字符时我遇到了问题。
示例:我在 url 中的模型是“this-f-example”,数据库中的模型是“this f-example”(因此没有第一个连字符)。
我编写了以下 php 代码,但这还不够。它只会在我的数据库中查找 this f example
或 this-f-example
,因此它不会返回任何内容,因为这些模型不存在。
我应该如何更改我的代码,以便它也能查找模型 this-f example
和 this f-example
?
完整网址:http//:www.example.com/test.php?model=this-f-example
数据库对应模型:这个f-example
<?php
$pdo = new PDO ('mysql:host.....');
$model1 = str_replace ('-', ' ', $_GET['model']);
$model2 = $_GET['model'];
$sql = "SELECT DISTINCT brand, model FROM `exampletable` WHERE model = :model1 OR model = :model2";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":model1", $model1);
$stmt->bindParam(":model2", $model2);
$stmt->execute();
if($result = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $result['brand'];
echo $result['model'];
}
?>
最佳答案
如果您在 url 中发送的变量 model
必须是 this-f-example
,您可以使用 preg_replace
而不是 str_replace
来获取 url 中模型的 model1
和 model2
。
试试这段代码:
$modelUrl= $_GET['model'];
$model1 = preg_replace('/-/', ' ', $modelUrl, 1);//remove the first hyphen
$occ = preg_match_all('/-/', $modelUrl, $matches, PREG_OFFSET_CAPTURE);
if ($occ !== false && $occ > 1) {
//remove the second hyphen
$model2 = substr_replace($modelUrl, ' ', $matches[0][2][1], strlen('-'));
}
$params = array(":model1"=> $model1,
":model2"=> $model2);
$sql = "SELECT DISTINCT brand, model FROM `exampletable` WHERE model=:model1 OR model=:model2";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
但如果您的问题只是变量中的空格,我认为更好的解决方案是使用 urlencode()
将使用 +
对变量中的空间进行编码的函数:
echo urlencode('this f-example'); // output : this+f-example
当您使用 $GET['model']
获取它时,只需使用 urldecode()
解码变量并删除 +
的函数:
echo urldecode($GET['model']); // output : this f-example
关于php - "Get"函数不起作用,因为不是所有的连字符都应该被替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29656406/