0

I have found out a code below

<?php $string = 'April 15, 2003'; 
$pattern = '/(\w+) (\d+), (\d+)/i'; 
$replacement = '${1}1,$3';

I just want to know why this 1 after ${1} is declaired and why the value 3 is assigned before the end of the string symbol ?

Avinash Babu
  • 6,171
  • 3
  • 21
  • 26

1 Answers1

3

If you execute the code as it is, you get:

April1,2003

This is because you are delimiting the variable $1 to separate it from what would be $11. Here's more on that.

If you change it, you get:

,2003

...because backreference $11 doesn't exist.

Why is $3 declared before the ending string symbol? Because it's part of the preg_replace backreference. If you move it outside of the replacement string, you'll see it crash and burn.

Footnote: why you're replacing this with <variable>1,<variable> seems really odd. That 1 is static - in that it never changes. I'd be more inclined to think you'd want a replacement like ${1}${2},$3 which would return April15,2003.

Community
  • 1
  • 1
brandonscript
  • 68,675
  • 32
  • 163
  • 220