【问题标题】:Add string before and after array values for php>mysql searching在 php>mysql 搜索的数组值之前和之后添加字符串
【发布时间】:2013-07-03 05:51:28
【问题描述】:

我有一个带有多个复选框的 html 表单。我将这些传递给 php...

例如,这些值将像“G,BW”一样出现(“BW,G”也需要匹配) 在 check.php 中,我需要从 $_GET 中获取值并修改它们以进行 sql 查询...

<?php
if(!empty($_GET['wireColor'])) {
    foreach($_GET['wireColor'] as $colors) {
    echo $colors; //make sure it's right, then comment out
    }
}

$colors = rtrim($colors, ','); //Get rid of trailing , - not working right

$wireSearch = '\'REGEXP \'.*(^|,).$wireColor.(,|$)\''; //Trying to add the sql bits to pass to the query.

理想情况下通过:

$colors_lookup_sql = "SELECT * FROM parts WHERE ( wire_colors REGEXP '.*(^|,)$wireSearch(,|$)' and wire_colors REGEXP '.*(^|,)$wireSearch(,|$)' );";

下面是查询在结尾的样子:

SELECT * FROM parts WHERE ( wire_colors REGEXP '.*(^|,)G(,|$)' and wire_colors REGEXP '.*(^|,)BW(,|$)' );

我很难将正则表达式位放入查询中。

更新

这是我现在拥有的:

<?php
if(!empty($_GET['wireColor'])) {
    foreach($_GET['wireColor'] as $colors) {
        $wireSearch = ' REGEXP \'.*(^|,)' .$colors.'(,|$)\' AND ';
    }
}

$Search = rtrim($wireSearch, 'AND'); //Trying to trim the last "AND"
$colors_lookup_sql = "SELECT * FROM parts WHERE ( wire_colors $wireSearch% );";

这主要给了我我需要的东西,但是打印/回显结果,我得到了:

$wireSearch 最终结果为:REGEXP '.*(^|,)G(,|$)' AND REGEXP '.*(^|,)BW(,|$)' AND 这太棒了——我只需要核对最后一个“AND”。不过,上面的修剪将其替换为第二个值。很奇怪。

$colors_lookup_sql 最终为:SELECT * FROM parts WHERE ( wire_colors REGEXP '.*(^|,)BW(,|$)' AND % );

但由于某种原因,数组中的第一个值消失了,我不明白,因为它出现在 sql 语句之前。

【问题讨论】:

    标签: php mysql regex


    【解决方案1】:

    我不确定查询中的正则表达式,因为我没有使用它,但是:

    $wireSearch = '\'REGEXP \'.*(^|,).$wireColor.(,|$)\'';
    

    这里你有一个问题,变量$wireColor 在一个字符串中,而你正在使用',所以里面的任何东西都不会被读取为变量,它应该是这样的:

    $wireSearch = '\'REGEXP \'.*(^|,)'.$wireColor.'(,|$)\'';
    

    【讨论】:

    • 这就是我逃离他们的原因 - 我会试一试。
    • 这很好,足以让我走得更远。查看我的更新。
    • 我会说这个问题已经解决了——尽管它把我带进了一个兔子洞。谢谢!
    【解决方案2】:

    我不能说我完全了解您的数据是如何存储的,而且我自己也没有经常使用 REGEX,但也许这样的东西会更容易使用:

    $wireSearch = explode(",", $_GET['wireColor']);
    $query = "SELECT * FROM parts WHERE wire_colors LIKE '%$wireSearch[0]%' 
             AND wire_colors LIKE '%$wireSearch[1]%'";
    

    不确定这是否有帮助,但我认为 id 提出了这个想法。

    【讨论】:

      【解决方案3】:

      我猜mysql正则表达式支持单词边界,怎么样:

      wire_colors REGEX '\bBW\b' and wire_colors regex '\bW\b'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多