I’ve got some bad MySQL entries that I need to fix. I’m trying to do so in PHP.
What I’ve got:
a whole bunch of text with no numbers Entry #:2439. a whole bunch of text Click here to blah blah blah
What I want:
a whole bunch of text with no numbers Entry #:2439. a whole bunch of text <BR><A href='somepage.php?entry_no=2439'>Click here to blah blah blah</A>
My PHP code:
$fixed = preg_replace('/(.*)(\d*)(.*)(Click here.*)/i','$1$2$3<BR><A href=\'somepage.php?entry_no=$2\'>$4</A>',$originalData);
For some reason, this is what I get:
a whole bunch of text with no numbers Entry #:2439. a whole bunch of text <BR><A href='somepage.php?entry_no='>Click here to blah blah blah</A>
The $2 is not giving me the number the second time. Anyone have any ideas?
It’s because the first match is being greedy:
Given this input, here’s what each part is matching:
All you have to do is make the first match non-greedy:
Also, since you’re defining the regex inside a string, you need to escape your slashes: