PHP mongo查找字段以

时间:2014-09-16 15:10:06

标签: php regex mongodb

我试图做一个像php mongo一样的mysql;在我的文章集中找到任何链接,这些链接以www.foo.com/{category}开头。我可以在shell中执行它,但PHP驱动程序似乎没有正确插入我的命令。 mongo正则表达式缺乏完整的文档。这是我的代码。

$cats = ['news', 'life', 'humor'];

foreach($cats as $cat){
    $category = 'www.foo.com/' . $cat;
    $articles = db()->articles->find(['link' => array('$regex'=>new MongoRegex("/^$category/"))]);
}

它返回文章但链接不匹配。

1 个答案:

答案 0 :(得分:1)

我尝试连接正则表达式,然后将其传递给mongo查询,而不是在查询中正则表达式,同时删除引号,这似乎工作。希望它可以帮助遇到类似问题的其他人

$cats = ['news', 'life', 'humor'];

foreach($cats as $cat){
    $prefix = '/^'; 
    $suffix = '/'; // prefix and suffix make up the regex notation for text that starts with 
    $category = $prefix . 'www.foo.com/' . $cat . $suffix;
    $articles = db()->articles->find(['link' => array('$regex'=>new MongoRegex($category))]);
}
相关问题