0

I'm using file_get_contents on a fairly large file. In it, I need to find every instance of:

http://www.example.com/?foo=1&bar=3

and change it to:

http://www.example.com?foo=1&bar=4

My problem is not understand how preg_replace will replace only a partial match on my regex and not the entire string. For example, pseudocode looks like the following:

 $content = file_get_contents($filename);
 $pattern = '/http:\/\/www\.example\.com/\?foo=1\&bar=(\d+)';
 preg_replace($pattern, "4", $content);
 file_put_contents($filename, $content);

I'm almost certain preg_replace($pattern, "4", $content); is wrong in this case. What's the right way to just replace the '3' with the '4'here?

3
  • Why not simply use str_replace? Commented Feb 10, 2016 at 0:05
  • Because bar=4 is not static. it might be bar=10, bar=12341324 etc. Commented Feb 10, 2016 at 0:06
  • 1
    you have missed closing regexp slash, and preg_replace will change whole pattern to '4', in your case. if you need to change just a one character, you can use @Enissay solution, but be ready, that his solution will change any digits with any length to '4'. If you need replacing exactly that string, you need additional limiting condition. Commented Feb 10, 2016 at 0:26

2 Answers 2

3

Use the \K: resets the starting point of the reported match. Any previously consumed characters are no longer included in the final match

$pattern = '/http:\/\/www\.example\.com\/\?foo=1\&bar=\K\d+/';
preg_replace($pattern, "4", $content);

DEMO

You can also use a lookbehind:

$pattern = '/(?<=http:\/\/www\.example\.com\/\?foo=1\&bar=)\d+/';
preg_replace($pattern, "4", $content);

DEMO

Sign up to request clarification or add additional context in comments.

Comments

0
$content = file_get_contents($filename);
$pattern = '/http:\/\/www\.example\.com\/\?foo=1\&bar=(\d+)/i';
$content = preg_replace($pattern, "http://www.example.com/?foo=1&bar=4", $content);
file_put_contents($filename, $content);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.