代码之家  ›  专栏  ›  技术社区  ›  Andrew Ensley

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

  •  0
  • Andrew Ensley  · 技术社区  · 16 年前

    我有一些糟糕的MySQL条目需要修复。我试着用PHP来实现。

    我有什么 :

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

    :

    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);
    

    一大堆没有数字的文本条目#: 2439 . a whole bunch of text <BR><A href="somepage.php?entry_no=">Click here to blah blah blah</A>

    1 回复  |  直到 12 年前
        1
  •  6
  •   nickf    16 年前

    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*) ...