“Get” function doesn't work because not all hyphens should be replaced

[亡魂溺海] 提交于 2019-12-11 10:37:28

问题


I use a Get function to look for the field model in an url but I have a problem when the model contains a space and a hyphen. Example: my model in the url is "this-f-example" and the model in the database is "this f-example" (so without the first hyphen).

I wrote the following php code, but it's not sufficient. It would only look for this f example or this-f-example in my database so it would return nothing because those models don't exist.

What should I change to my code so it would look for the models this-f example and this f-example too?

Complete url: http//:www.example.com/test.php?model=this-f-example

Corresponding model in database: this 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'];
    }
?>

回答1:


You could use Regular Expressions.

// turn 'this-f-model' to 'this[- ]f[- ]example'
$model = str_replace ('-', '[- ]', $_GET['model']);

$sql = "SELECT DISTINCT brand, model FROM `exampletable` WHERE model REGEXP :model";

$stmt = $pdo->prepare($sql);
$stmt->bindParam(":model", $model);
$stmt->execute();



回答2:


If the variable model that you're sending in url must be this-f-example, you could use preg_replace instead of str_replace to get your model1 and model2 for the model in the url.

Try with this code :

$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);

But if your problem is just the spaces in your variabale, I think a better solution is to use the urlencode() function which will encode the space in your varibale with + :

echo urlencode('this f-example'); // output : this+f-example

And when you get it with $GET['model'], just use the urldecode() function to decode the varibale and remove the + :

echo urldecode($GET['model']); // output : this f-example

Hope this could help.



来源:https://stackoverflow.com/questions/29656406/get-function-doesnt-work-because-not-all-hyphens-should-be-replaced

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!