Replace with a constant value
After replace()
, you need to explicitly use one of first()
/all()
/only(int)
methods, to express how many
replacements should be done.
Specifying limits is done to relieve you from brain strain - so you can immediately recognize author's intentions.
#
LimitsUsing first()
/all()
/only(int)
is semantically identical to passing $limit
argument to
preg_replace()
/preg_replace_callback()
.
first()
#
First occurrence - - T-Regx
- PHP
all()
#
All occurrences - - T-Regx
- PHP
only()
#
Limited occurrences - - T-Regx
- PHP
Read on, to learn more about replacing with a callback.
#
Regular expression referencesNormally, had you passed a replacement to preg_replace()
, that contains a backslash or a dollar sign followed by a
number (eg. \1
or $2
) - that reference would be replaced by a corresponding capturing group (or by an empty string,
if the group wasn't matched).
Resolving such references won't happen using with()
.
This is done to relieve you from the brain strain. A programmer should be able to merely
replace a string with a constant value without cognitive load about possible \
or $
hiding somewhere.
- T-Regx
- PHP
You can be sure, what's put into with()
will certainly be present unchanged in your final result.
Some replacement strings containing a backslash or a dollar sign (like file system paths, URL addresses or even user input) might interfere with logic and cause bugs that are very hard to find.
note
Neither of types of references are resolved: $12
, \12
nor ${12}
.
#
PHP-style intentional referencesIf you, however, would like to intentionally use regular expression references and have validated your input
against an unexpected \
or $
- feel free to use withReferences()
which will resolve replacement references.
- T-Regx
- PHP
However, this is not recommended. For that, try using replace()->callback()
.
The only valid use-cases for withReferences()
is:
- Performance (since
withReferences()
usespreg_replace()
, and notpreg_replace_callback()
) - Migration from
preg_replace()
used in legacy codebase
note
Using withReferences()
is not recommended, since it exposes part of PHP regexps API, and
isn't actually part of T-Regx. Instead, try using with()
or callback()
.
We don't encourage its usage, but we're keeping it nonetheless, to allow users to decide for themselves whether they want to use T-Regx API, or stay with PHP replace style.
#
Remove occurrenceThere are times when you'd like to simply remove the occurrence of a pattern from your subject. To do that,
use pattern()->prune()
instead of pattern()->replace()
:
- T-Regx
- PHP
It's actually identical to calling replace()->with('')
under the hood, but it's a bit shorter and more expressive.