How to remove white space in the output file of this regular expression?

I use 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 20 and 14 to get the result of 2014 . How to do it?

+8
php regex preg-replace preg-match
source share
4 answers

You could just do it

 $s="2044 blablabla 2033 blablabla 2088"; echo preg_replace("/(20\d\d)/","2014",$s); 
+4
source share

You need to use curly braces inside single quotes:

 echo preg_replace("/(20)\d\d/",'${1}14',$s); 
+12
source share

After checking the preg_replace :

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

Therefore use

 "\${1}14" 

or

 '${1}14' 
+7
source share

You need to use the preg_replace_callback() function:

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

All Articles