tags:

views:

290

answers:

2

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?

A: 

Check this out might help you http://ca.php.net/preg_replace

Pooria
+6  A: 

It's because the first match is being greedy:

Given this input, here's what each part is matching:

a whole bunch of text with no numbers Entry #: 2439. a whole bunch of text Click here to blah blah blah

(.*)    // "a whole bunch of text with no numbers Entry #: 2439. a whole bunch of text "
(\d*)   // "" (0 or more numbers)
(.*)    // "" (0 or more characters)

All you have to do is make the first match non-greedy:

(.*?)(\d+)(.*)(Click here.*)

Also, since you're defining the regex inside a string, you need to escape your slashes:

"/(.*?)(\\d*) ...
nickf
Thanks for you help. I added the ? to the first match and escaped the backslash, but it still returns the same results.
Andrew
Got it! Using what you gave me, I tried changing the first match to (.*Entry #: ) and it worked. Thanks very much.
Andrew
oh - you could also change the \d* to \d+ to make sure it matches at least one number.
nickf