问题
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