带有正则表达式字符类的CDbCriteria参数 [英] CDbCriteria parameters with regex character classes

查看:97
本文介绍了带有正则表达式字符类的CDbCriteria参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在条件为REGEXP的Yii中使用CDbCriteria.我正在使用MySQL标记来标记单词边界,分别为[[:<:]][[:>:]],但这似乎与Yii冲突,因为我得到无效的参数编号:绑定变量的数量与标记的数量不匹配".我认为这是因为单词边界标记使用冒号,这也是用于绑定参数的内容.有办法解决吗?

I'm trying to use CDbCriteria in Yii with a REGEXP condition. I'm using the MySQL markers for word boundaries, being [[:<:]] and [[:>:]], however this seems to conflict with Yii because I get "Invalid parameter number: number of bound variables does not match number of tokens". I assume this is because the word boundary markers use a colon, which is also what is used for binding parameters. Is there a way around this?

    $criteria = new CDbCriteria;
    $criteria->addCondition('col regexp "[[:<:]]:app[[:>:]]"');
    $criteria->params = array(':app'=>$app);
    $details = Post::model()->find($criteria);

推荐答案

PHP不会替换字符串内(即引号内)的占位符.如:

PHP will not replace placeholders inside strings, i.e within quotes. As in:

$criteria->addCondition('col = :app'); // param can be replaced
$criteria->addCondition('col = ":app"'); // param can't be replaced

因此,我们需要使用mysql的

Therefore we need to use mysql's CONCAT() function to actually generate the string for regexp, instead of providing the string ourselves, like so:

$criteria->addCondition('col regexp CONCAT("[[:<:]]", :app, "[[:>:]]")');

或者,绑定整个正则表达式本身:

OR, bind the entire regex itself:

$criteria->addCondition('col regexp :regexp');
$criteria->params = array(':regexp'=>'[[:<:]]'.$app.'[[:>:]]');

这篇关于带有正则表达式字符类的CDbCriteria参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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