CakeFest 2024: The Official CakePHP Conference

MongoDB\BSON\Regex::__construct

(mongodb >=1.0.0)

MongoDB\BSON\Regex::__constructConstruct a new Regex

Description

final public MongoDB\BSON\Regex::__construct(string $pattern, string $flags = "")

Parameters

pattern (string)

The regular expression pattern.

Note: The pattern should not be wrapped with delimiter characters.

flags (string)

The » regular expression flags. Characters in this argument will be sorted alphabetically.

Errors/Exceptions

Changelog

Version Description
PECL mongodb 1.2.0

The flags argument is optional and defaults to an empty string.

Characters in the flags argument will be sorted alphabetically when a Regex is constructed. Previously, the characters were stored in the order provided.

MongoDB\Driver\Exception\InvalidArgumentException is thrown if pattern or flags contain null bytes. Previously, values would be truncated at the first null byte.

Examples

Example #1 MongoDB\BSON\Regex::__construct() example

<?php

$regex
= new MongoDB\BSON\Regex('^foo', 'i');
var_dump($regex);

?>

The above example will output:

object(MongoDB\BSON\Regex)#1 (2) {
  ["pattern"]=>
  string(4) "^foo"
  ["flags"]=>
  string(1) "i"
}
add a note

User Contributed Notes 1 note

up
4
Alejandro Wilcke
4 years ago
This matches with any fieldName that includes the string:
$mongoRegex = new MongoDB\BSON\Regex("$string", "i");

This matches with any fieldName that STARTS with the string:
$mongoRegex = new MongoDB\BSON\Regex("^$string", "i");

$cursor = $collection->find( [ 'fieldName' => $mongoRegex ] );

$docs = [];

foreach($cursor as $doc){
$docs[] = $doc;
}

return $docs;
To Top