Question

I'm trying to replace a version string but it always eats up my fists letter of the version string until I put a space in between: Version:$1 $new_version

But I do not want to do that and would like to understand what happens here.

File contents:

Version:    4.4.4

Relevant part of my code:

$new_version = 6.6.6
$new_main_file_content = preg_replace(
    '/Version:([ ]*)[0-9\.]+/', 
    "Version:$1$new_version", 
    file_get_contents($main_file) 
);

Without the space the output is Version:.6.6 and with it, the output is right but just one space too much. I have tried using the curly brackets as well, but... no luck.

Was it helpful?

Solution

This is a replacement gotcha. From the PHP manual documentation on preg_replace():

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.

This should do what you want:

preg_replace( '/Version:([ ]*)[0-9\.]+/', 'Version:${1}'.$new_version, ...);

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top