为什么这个PHP preg_replace()不起作用?

时间:2009-03-05 05:46:31

标签: php mysql regex

我有一些我需要解决的错误的MySQL条目。我试图在PHP中这样做。

我得到了什么

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 <BR><A href="somepage.php?entry_no= 2439 ">Click here to blah blah blah</A>

我的PHP代码

$fixed = preg_replace('/(.*)(\d*)(.*)(Click here.*)/i',"$1$2$3<BR><A href=\"somepage.php?entry_no=$2\">$4</A>",$originalData);

出于某种原因,这就是我得到的:

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>

2美元不是第二次给我这个号码。有人有什么想法吗?

1 个答案:

答案 0 :(得分:6)

这是因为第一场比赛是贪婪的:

鉴于此输入,以下是每个部分匹配的内容:

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)

你所要做的就是让第一场比赛变得非贪婪:

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

此外,由于您在字符串中定义正则表达式,因此需要转义斜杠:

"/(.*?)(\\d*) ...