Skip to content

Commit 0819ef5

Browse files
committed
Tweak regexp operations, fixes #282
1 parent 5f755fe commit 0819ef5

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

src/Jenssegers/Mongodb/Query/Builder.php

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -832,13 +832,30 @@ protected function compileWhereBasic($where)
832832
$operator = '=';
833833
$regex = str_replace('%', '', $value);
834834

835-
// Prepare regex
836-
if (substr($value, 0, 1) != '%') $regex = '^' . $regex;
837-
if (substr($value, -1) != '%') $regex = $regex . '$';
835+
// Convert like to regular expression.
836+
if (starts_with($value, '%')) $regex = '^' . $regex;
837+
if (ends_with($value, '%')) $regex = $regex . '$';
838838

839839
$value = new MongoRegex("/$regex/i");
840840
}
841841

842+
// Manipulate regexp operations.
843+
elseif (in_array($operator, array('regexp', 'not regexp', 'regex', 'not regex')))
844+
{
845+
// Automatically convert regular expression strings to MongoRegex objects.
846+
if ( ! $value instanceof MongoRegex)
847+
{
848+
$value = new MongoRegex($value);
849+
}
850+
851+
// For inverse regexp operations, we can just use the $not operator
852+
// and pass it a MongoRegex instence.
853+
if (starts_with($operator, 'not'))
854+
{
855+
$operator = 'not';
856+
}
857+
}
858+
842859
if ( ! isset($operator) or $operator == '=')
843860
{
844861
$query = array($column => $value);

tests/QueryBuilderTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,12 @@ public function testOperators()
540540
$results = DB::collection('users')->where('name', 'REGEX', $regex)->get();
541541
$this->assertEquals(2, count($results));
542542

543+
$results = DB::collection('users')->where('name', 'regexp', '/.*doe/i')->get();
544+
$this->assertEquals(2, count($results));
545+
546+
$results = DB::collection('users')->where('name', 'not regexp', '/.*doe/i')->get();
547+
$this->assertEquals(1, count($results));
548+
543549
DB::collection('users')->insert(array(
544550
array(
545551
'name' => 'John Doe',

0 commit comments

Comments
 (0)