"获取"函数不起作用,因为并非所有连字符都应该被替换 [英] "Get" function doesn't work because not all hyphens should be replaced

查看:162
本文介绍了"获取"函数不起作用,因为并非所有连字符都应该被替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Get函数在url中寻找字段 model ,但是当模型包含空格和连字符时,我遇到了问题。
例如:我在url中的模型是 this-f-example ,而数据库中的模型是这个f-example 第一个连字符)。

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).

我写了下面的php代码,但这还不够。它只会在我的数据库中查找这个例子 this-f-example ,所以它不会返回任何内容,因为这些模型不存在。

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.

我应该更改我的代码,以便查找模型 this-f示例这个f-example 呢?

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

完整的网址: http //: www.example.com/test.php?model=this-f-example

数据库中的相应模型:这个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'];
    }
?>


推荐答案

您可以使用 正则表达式

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

这篇关于&QUOT;获取&QUOT;函数不起作用,因为并非所有连字符都应该被替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆