Replace by map

There are cases when you have to use more than one replacement, but you also don't need Match details or any replacement logic, really, so both with() and callback() are a little unfit.

Replacing by map allows T-Regx to save a little performance overhead, by not creating Match object.

Standard map

  • T-Regx
  • PHP
$message = 'My words: "mp3", "mp4", "gif"';
'mp3' => 'Audio file',
'mp4' => 'Video file',
'gif' => 'Animation'
My words: "Audio file", "Video file", "Animation"

And of course all()/first()/only(int) modifiers are taken into account.

Superfluous matches

Normally, had you found a match that's not present in your map - MissingReplacementKeyException would be thrown (as long as gif is matched by your pattern, of course):

$message = 'My words: "mp3", "mp4", "gif"';
'mp3' => 'Audio file',
'mp4' => 'Video file'
// 'gif' => 'Animation'

If you don't need to specify all your possible [match => replacement] pairs, you should use one of the below mapIfExists().

Ignored replacements

With mapIfExists() - superfluous occurrences are left unchanged:

  • T-Regx
  • PHP
$message = "Extensions: mp3, mp4, jpg, jpeg, png, gif";
'mp3' => 'Audio',
'gif' => 'Animation'
Extensions: Audio, mp4, jpg, jpeg, png, Animation


Resolving a replacement based on a whole match however, is both uncommon and unpractical. It's much more elastic to resolve it based on a specific capturing group, using by()->group()->map():

  • T-Regx
  • PHP
$links = 'Links:,,,';
'google' => 'Search Engine',
'socket' => 'Documentation',
'facebook' => 'Social Portal',
't-regx' => 'Documentation',
Links: Search Engine, Documentation, Social Portal, Documentation
Last updated on