Automatic delimiters

note

This chapter doesn't contain PHP code snippets, because PHP PCRE require delimiters. There is no way to omit them in Vanilla PHP.

Overview#

Thanks to automatic delimiters, one can use regular expressions without brain strain and without spending time, choosing a suitable delimiter.

pattern('#[A-Z]/[a-z]+')->match($subject)->all();

Delimited pattern#

Calling method delimited() on any instance of T-Regx PatternInterface returns a pattern, as it will be used with PHP PCRE methods.

echo pattern('Welcome/Or not')->delimited() . "\n";
echo pattern('https://github.com#heading')->delimited() . "\n";
echo pattern('https://github.com#heading?key=hello%20there')->delimited() . "\n";
#Welcome/Or not#
%https://github.com#heading%
~https://github.com#heading?key=hello%20there~

PCRE-style patterns#

If the was constructed with Pattern::pcre(), method delimited() returns the pattern unchanged.

Pattern::pcre('#Welcome/Or not#')->delimited();
#Welcome/Or not#

Flags#

There are two ways of using patterns with PCRE modifiers:

  • Either pass a second argument to pattern()/Pattern::of():

    // global function
    pattern('[A-Z][a-z]+', 'i')->match($subject)->first();
    // static method
    Pattern::of('[A-Z][a-z]+', 'i')->match($subject)->first();
    // prepared patterns
    Pattern::inject('[A-Z]@', [$_GET['name']], 'i')->match($subject)->first();
  • or use an old-school pattern:

    Pattern::pcre('/[A-Z][a-z]+/i')->match($subject)->first();

I want to break it#

T-Regx has a set of predefined, suitable delimiters (like /, #, ~, %, etc.) and simply uses the first one, that doesn't occur in your pattern. If you exhaust each of them; if you use every possible, predefined, suitable delimiter - it will throw ExplicitDelimiterRequiredException.

In that case, you simply have to use an explicit delimiter with Pattern::pcre().

If you think another automatic delimiter can be used, please create a github issue.

Last updated on