Match a subject

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

Test a subject

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

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

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

  • T-Regx
  • PHP
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

Many

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

  • T-Regx
  • PHP
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).

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

One

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

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

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

Unmatched subject

all()/only()

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

  • T-Regx
  • PHP
pattern('\d+')->match('Word')->all();
[]

first()

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

  • T-Regx
  • PHP
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