Skip to main content

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 - otherwise()/throwingOtherwise()/returningOtherwise()

Limiting replacements#

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

$subject = "I'm 19, I have 192cm and I was born in 1999";
"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