Match a subject

Using pattern()->match() you can:

Test a subject

If you only need to check whether a pattern matches a subject, use:

pattern('[0-9]+')->test("I'm 19 years old");

...or to check whether it doesn't:

pattern('[0-9]{3}')->fails("I'm 19 years old");

Of course pattern()->match() throws an exception if the pattern is invalid (or in case of any other error).

You can also use pattern()->match()->test() and pattern()->match()->fails().

Retrieve matches


You can easily retrieve matched occurrences of a pattern in your subject.

pattern('[0-9]+')->match("I'm 19. I was born in 1999, on May 12")->all();
['19', '1999', '12']

You can limit your matches with only(int).

pattern('[0-9]+')->match("I'm 19. I was born in 1999, on May 12")->only(2);
['19', '1999']


To get the first occurrence of a matched pattern, call first().

pattern('[0-9]+')->match("I'm 19 years old. I was born in 1999")->first();

Read on the next page to learn more about first().

Unmatched subject


If you call all() or only() on a subject that doesn't match your pattern, you'll receive an empty array.



If, however, subject doesn't match your pattern and you use first() - SubjectNotMatchedException is thrown.

try {
return pattern('\d+')->match('Word')->first();
catch (SubjectNotMatchedException $e) {
// handle

Protect the developer

Please, keep in mind that T-Regx aims to relieve you (a programmer) from any brain strain, therefore if you

Last updated on