【问题标题】:ZF2 - MySQL Regex for Whole word searchesZF2 - 用于全词搜索的 MySQL 正则表达式
【发布时间】:2014-12-30 16:31:09
【问题描述】:

假设:您在 ZF2 模型中有一个正常的子字符串搜索。你如何把它变成一个全词搜索?

【问题讨论】:

    标签: php mysql regex zend-framework2


    【解决方案1】:

    一种方法是在谓词表达式中使用 MySQL REGEXP 调用。

    其中$selectZend\Db\Sql\Select 的一个实例,$searchFor 是您的搜索词:

    原始子字符串搜索可能会使用这样的 where...

    $select->where(array(
        new Predicate\PredicateSet(
            array(
                new Zend\Db\Sql\Predicate\Like('tag', '%' . $searchFor . '%'),
                new Zend\Db\Sql\Predicate\Like('title', '%' . $searchFor . '%'),
            ),
            Zend\Db\Sql\Predicate\PredicateSet::COMBINED_BY_OR
        ),
    ));
    

    ...上面的全词版本是:

    $select->where(array(
        new Predicate\PredicateSet(
            array(
                new Zend\Db\Sql\Predicate\Expression("tag REGEXP '([[:<:]]" . $searchFor ."[[:>:]])'"),
                new Zend\Db\Sql\Predicate\Expression("title REGEXP '([[:<:]]" . $searchFor ."[[:>:]])'"),
            ),
            Zend\Db\Sql\Predicate\PredicateSet::COMBINED_BY_OR
        ),
    ));
    

    请注意,这些是多字段搜索,所以我完成了PredicateSet::COMBINED_BY_OR。我花了很长时间才停止在我的正则表达式中使用\b。希望这可以节省一些时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 2012-03-10
      • 1970-01-01
      • 2012-02-23
      • 1970-01-01
      相关资源
      最近更新 更多