7

I've been using the following site to test a PHP regex so I don't have to constantly upload: http://www.spaweditor.com/scripts/regex/index.php

I'm using the following regex:

/(.*?)\.{3}/

on the following string (replacing with nothing):

Non-important data...important data...more important data

and preg_replace is returning:

more important data

yet I expect it to return:

important data...more important data

I thought the ? is the non-greedy modifier. What's going on here?

AndersTornkvist
  • 2,610
  • 20
  • 38
Jeff Lamb
  • 5,755
  • 4
  • 37
  • 54
  • What settings are you using on the site you linked? I just tried it and got back "Non-important data" as I expected. Your regular expression is finding the first match, and grabbing as little as it can before it can find a `...`. – Doug Neiner Dec 14 '09 at 06:03
  • @Doug Neiner: On his website link, make sure you select `preg_replace` in the last section. I was able reproduce the OP's results this way. – Asaph Dec 14 '09 at 06:07
  • 1
    Ah, very true. Picked the wrong one. – Doug Neiner Dec 14 '09 at 06:19

2 Answers2

10

Your non-greedy modifier is working as expected. But preg_match replaces all occurences of the the (non-greedy) match with the replacement text ("" in your case). If you want only the first one replaced, you could pass 1 as the optional 4th argument (limit) to preg_replace function (PHP docs for preg_replace). On the website you linked, this can be accomplished by typing 1 into the text input between the word "Flags" and the word "limit".

Asaph
  • 159,146
  • 25
  • 197
  • 199
  • 1
    +1 @Asaph, great answer. I had chosen `preg_match` instead of `preg_replace` when I tried out the link, so it through me of the scent. You are of course completely correct in your answer! – Doug Neiner Dec 14 '09 at 06:18
0

just an actual example of @Asaph solution. In this example ou don't need non-greediness because you can specify a count. replace just the first occurrence of @ in a line with a marker

 $line=preg_replace('/@/','zzzzxxxzzz',$line,1);
zzapper
  • 4,743
  • 5
  • 48
  • 45