CDbCriteria parameters with regex character classes

送分小仙女□ 提交于 2020-01-04 02:07:15

问题


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

回答1:


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

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.'[[:>:]]');


来源:https://stackoverflow.com/questions/17893178/cdbcriteria-parameters-with-regex-character-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!