Replacing a string

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

  • Limit replacements with:
    • replace()->first()
    • replace()->all()
    • replace()->only(int)
  • replace with a constant value - with()/withReferences()
  • replace with a computed value - callback()
  • replace based on an associative array - by()->map()
  • replace with a capturing group - by()->group()
  • handle subjects that don't match the pattern for replacements - orElse()/orReturn()/orThrow()

Limiting replacements

After replace(), you need to explicitly use one of first()/all()/only(int) methods, to express how many replacements should be done.

  • T-Regx
  • PHP
$subject = "I'm 19, I have 192cm and I was born in 1999";
pattern('\d+')->replace($subject)->first()->with('___');
pattern('\d+')->replace($subject)->only(2)->with('___');
pattern('\d+')->replace($subject)->all()->with('___');
"I'm ___, I have 192cm and I was born in 1999"
"I'm ___, I have ___cm and I was born in 1999"
"I'm ___, I have ___cm and I was born in ___"

Read on to learn more about replacing with a constant value.

Last updated on