views:

862

answers:

1

Hi, I've got a project I'm working on converting some legacy perl cgi forms to PHP. A lot of this requires finding / replacing information. In one such case, I have lines like this in the perl script:

<INPUT type="radio" name="trade" value="1" $checked{trade}->{1}>

which needs to read:

<INPUT type="radio" name="trade" value="1" <?php echo checked('trade', 1); ?>>

Another example to show some variation in how these tags might show up in the perl/html:

<INPUT type="radio" name="loantype" value="new" $checked{loantype}->{new}>
<INPUT type="radio" name="loantype" value="new" $checked{'loantype'}->{new}>
<INPUT type="radio" name="loantype" value="new" $checked{'loantype'}->{'new'}>
<INPUT type="radio" name="loantype" value="new" $checked{loantype}->{'new'}>

As you can see, the quotes can be about anywhere, but that's not my problem. I decided to write a find / replace regex in textmate to make my life a bit easier. My Regex looks like:

Find:     \$checked\{'?([^']+)'?\}->\{'?([^']+)'?\}
Replace:  <?php echo checked('$1', '$2'); ?>

This worked fine in the first file I did it with, but for some reason in the current file the Regex has become really greedy, matching many lines. it'll match the begininng (\$checked...) and then match up to the last time the character '}' appears. I've tried a few variations to make it a bit less greedy including:

 ^(.*)\$checked\{'?([^']+)'?\}->\{'?([^']+)'?\}(.*)$

But even that seems to match multiple lines. I assumed the ^ at the beginning would only match the beginning of a line, and the $ at the end would only match the end... constraining my match to 1 line... but it doesn't it seems.

/me fails at regex

Thanks for any help, Mike

+2  A: 

Try this:

^(.*?)\$checked\{'?([^']+?)'?\}->\{'?([^']+?)'?\}(.*?)$

The ? after * and + make them "non-greedy".

Gordon Wilson
Thanks, that works perfectly.
Electronic Zebra