Skip to content

Latest commit

 

History

History
72 lines (55 loc) · 2.67 KB

preg_match_transformer.md

File metadata and controls

72 lines (55 loc) · 2.67 KB

PregMatchTransformer

Perform a regular expression match, using PHP's preg_match or preg_match_all function, and return the matches.

Transformer reference

  • Service: CleverAge\ProcessBundle\Transformer\String\PregMatchTransformer
  • Transformer code: preg_match

Accepted inputs

string, or a scalar or a \Stringable cast to a string. null gives null. An array or another object (a \BackedEnum included) throws an UnexpectedValueException.

Possible outputs

  • array: the $matches array filled by preg_match / preg_match_all (an empty array when nothing matches with preg_match)
  • null if the input is null or an empty string

An invalid regular expression is rejected with an InvalidOptionsException when the options are resolved. A PCRE error while matching (e.g. invalid UTF-8 with the u modifier, backtracking limit reached) throws an UnexpectedValueException with the PCRE error message, instead of being taken for "no match".

Options

Code Type Required Default Description
pattern string X The regular expression, with delimiters
flags int 0 PREG_* flags passed to the function (e.g. !php/const PREG_OFFSET_CAPTURE)
offset int 0 Offset (in bytes) from which to start the search
mode_all bool false If true, use preg_match_all instead of preg_match

Examples

  • 'foobarbaz' becomes ['foobarbaz', 'foo', 'bar', 'baz']
# Transformer options level
preg_match:
  pattern: '/(foo)(bar)(baz)/'
  • Capture offsets and keep only the 2nd group: 'foobarbaz' becomes ['bar', 3]
# Transformer mapping level
second_group:
  code: '[text]'
  transformers:
    preg_match:
      pattern: '/(foo)(bar)(baz)/'
      flags: !php/const PREG_OFFSET_CAPTURE
    property_accessor:
      property_path: '[2]'
  • Get all numbers of a string: 'a1b22c333' becomes [['1', '22', '333']]
# Transformer options level
preg_match:
  pattern: '/\d+/'
  mode_all: true