Skip to content

Core\Regex::matches

Checks whether a pattern matches a text, and returns true or false.

The pattern can match at any position in the text. To check the whole text, start the pattern with ^ and end it with $. The pattern is a string or a Core\Regex\Pattern from Core\Regex::compile. Use a Pattern when you need options, such as matching upper and lower case letters the same way.

Good to know: matches only returns true or false. To read the matched text or its groups, use Core\Regex::match.

Parameters

  • $subjectstringThe text to search.
  • $patternCore\Regex\Pattern|stringA Core\Regex\Pattern from Core\Regex::compile, or a pattern string with no options. A tainted string does not compile here.

Return value

Returns bool. true if the text contains at least one match, and false if it does not.

Errors

  • RuntimeError$pattern is not a valid regular expression, or matching it against $subject needs more steps than the limit allows.

Examples

Does the text contain a number

<?nvs
// Shows how to check whether a text contains a number.
array<string> $messages = ['Table for 4 people', 'Table for four people'];
// `\d` matches one digit. The first message has one, so this prints "yes".
// The second message has no digit, so this prints "no".
foreach ($messages as string $message) {
echo $message, ': ', Core\Regex::matches($message, '\d') ? 'yes' : 'no', "\n";
}
Output
Table for 4 people: yes
Table for four people: no

Match the whole text

<?nvs
// Shows the difference between a match anywhere in the text and a match of the whole text.
string $code = 'AB-1234 extra';
// Without `^` and `$`, the pattern can match a part of the text. This prints "true".
echo Core\Regex::matches($code, '[A-Z]{2}-\d{4}') ? 'true' : 'false', "\n";
// With `^` and `$`, the whole text must match. The text has " extra" at the end,
// so this prints "false".
echo Core\Regex::matches($code, '^[A-Z]{2}-\d{4}$') ? 'true' : 'false', "\n";
Output
true
false

Check a username in a form

<?nvs
// Shows how to check a username from a form before you save it.
// A username has 3 to 16 characters: letters, digits and `_`.
// `caseInsensitive` makes `[a-z]` match upper case letters too.
Core\Regex\Pattern $username = Core\Regex::compile('^[a-z0-9_]{3,16}$', { caseInsensitive: true });
array<string> $inputs = ['Anna_92', 'jo', 'bob smith'];
// "Anna_92" is valid. "jo" is too short, and "bob smith" has a space.
foreach ($inputs as string $input) {
if (Core\Regex::matches($input, $username)) {
echo $input, ": saved\n";
} else {
echo $input, ": use 3 to 16 letters, digits or _\n";
}
}
Output
Anna_92: saved
jo: use 3 to 16 letters, digits or _
bob smith: use 3 to 16 letters, digits or _