8

I’m using regex in PHP. This is my script:

$s="2044 blablabla  2033 blablabla 2088";
echo preg_replace("/(20)\d\d/","$1 14",$s);

The result was like this:

20 14 blablabla 20 14 blablabla 20 14

I want to remove the space between the 20 and the 14 to get the result 2014. How do I do that?

TRiG
  • 10,148
  • 7
  • 57
  • 107
ro0xandr
  • 105
  • 7

4 Answers4

12

You need to use curly brackets inside single quotes:

echo preg_replace("/(20)\d\d/",'${1}14',$s);
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
7

After checking the preg_replace manual:

When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar \\1 notation for your backreference. \\11, for example, would confuse preg_replace() since it does not know whether you want the \\1 backreference followed by a literal 1, or the \\11 backreference followed by nothing. In this case the solution is to use \${1}1. This creates an isolated $1 backreference, leaving the 1 as a literal.

Therefore, use

"\${1}14"

or

'${1}14'
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
4

You could simply do like this,

$s="2044 blablabla  2033 blablabla 2088";
echo preg_replace("/(20\d\d)/","2014",$s);
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
2

You need to use preg_replace_callback() function:

echo preg_replace_callback("/(20)\d\d/", function($number) {
    return $number[1].'14';
},$s);

// 2014 blablabla 2014 blablabla 2014
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291