Core\Regex::matches
Core\Regex::matches(
string $subject,
Core\Regex\Pattern|string $pattern,
): boolChecks 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|stringACore\Regex\PatternfromCore\Regex::compile, or a pattern string with no options. Ataintedstring 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$patternis not a valid regular expression, or matching it against$subjectneeds 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";}Table for 4 people: yesTable for four people: noMatch 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";truefalseCheck 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"; }}Anna_92: savedjo: use 3 to 16 letters, digits or _bob smith: use 3 to 16 letters, digits or _