“Get” function doesn't work because not all hy

2019-08-15 04:35发布

问题:

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.