Results 1 to 2 of 2

Thread: Can't use brackets in preg_replace

  1. #1
    Join Date
    Apr 2006
    Posts
    32
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Can't use brackets in preg_replace

    Code:
      $find = array(
           "'<a href=\"(.*?)\" title=\"(.*?)\" tabindex=\"(.*?)\">diff</a>'i",
           "'<a href=\"(.*?)\" title=\"(.*?)\">hist</a>'i",
      );
      $replace = array(
           "<a href=\"\\1\" title=\"\\2\" tabindex=\"\\3\"><img src=\"http://wprcph.a2h.8m6.net/diff.gif\" alt=\"diff\" /></a>",
           "<a href=\"\\1\" title=\"\\2\"><img src=\"http://wprcph.a2h.8m6.net/hist.gif\" alt=\"hist\" /></a>",
      );
    
    $out6=preg_replace($find,$replace,$out5);
    See that code? It runs perfectly fine.

    But it doesn't when I try to do this:
    Code:
      $find = array(
           "'(<a href=\"(.*?)\" title=\"(.*?)\" tabindex=\"(.*?)\">diff</a>)'i",
           "'(<a href=\"(.*?)\" title=\"(.*?)\">hist</a>)'i",
      );
      $replace = array(
           "<a href=\"\\1\" title=\"\\2\" tabindex=\"\\3\"><img src=\"http://wprcph.a2h.8m6.net/diff.gif\" alt=\"diff\" /></a>",
           "<a href=\"\\1\" title=\"\\2\"><img src=\"http://wprcph.a2h.8m6.net/hist.gif\" alt=\"hist\" /></a>",
      );
    
    $out6=preg_replace($find,$replace,$out5);
    I wish to kill the brackets that surrond the diff and hist links, but as soon as I try the whole layout screws.

    Any help?

  2. #2
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Brackets are a special character in regex and must be escaped accordingly:
    Code:
      $find = array(
           '/\(<a href="(.*?)" title="(.*?)" tabindex="(.*?)">diff</a>\)/i',
           '/\(<a href="(.*?)" title="(.*?)">hist</a>\)/i',
      );
      $replace = array(
           '<a href="$1" title="$2" tabindex="$3"><img src="http://wprcph.a2h.8m6.net/diff.gif" alt="diff"></a>',
           '<a href="$1" title="$2"><img src="http://wprcph.a2h.8m6.net/hist.gif" alt="hist"></a>',
      );
    Don't overuse double quotes in PHP. They're slightly less efficient, and often considerably less readable, as seen here. Also, $n is now the preferred way of referencing a capture.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •