commit 726f774f99c7f0d17cdf6236ad54e7775da632d5
Author: Matteo Scaramuccia <moodle@matteoscaramuccia.com>
Date:   Tue Jul 3 21:59:59 2012 +0200

    MDLSITE-1146 "/bug #?(\d)+/i" behaviour differs from "/(MDL|MDLSITE|CONTRIB)-(\d+)/" one

diff --git a/filter.php b/filter.php
index bc7cd9d..bc362c1 100644
--- a/filter.php
+++ b/filter.php
@@ -47,12 +47,14 @@ class filter_moodlelinks extends moodle_text_filter {
                 '<a title="Auto-link to Moodle Tracker" href="http://tracker.moodle.org/browse/$0">$0</a>',
                 $text);
 
-        $text = eregi_replace("bug ([0-9]+)",
-                "<a title=\"Auto-link to Moodle Tracker\" href=\"http://tracker.moodle.org/browse/MDL-\\1\">MDL-\\1</a>", 
-                $text);
-
-        $text = eregi_replace("bug #([0-9]+)",
-                "<a title=\"Auto-link to Moodle Tracker\" href=\"http://tracker.moodle.org/browse/MDL-\\1\">MDL-\\1</a>", 
+        $regexp = '$' .
+                  'bug #?(\d+)' . // The basic pattern we are trying to match (\d is any digit).
+                  '\b' . // At the end of a word, That is, we don't want to match MDL-123xyz, but we don't care if we are followed by a space, punctionation or ...
+                  '(?![^\'"<>]*[\'"]\s*(?:\w+=[\'"][^\'"]*[\'"])*\\\?>)' . // Try to avoid matching if we are inside a HTML attribute. relies on having moderately well-formed HTML.
+                  '(?![^<]*</a>)' . // Try to avoid matching inside another link. Can be fooled by HTML like: <a href="..."><b>MDL-123</b></a>.
+                  '$i';
+        $text = preg_replace($regexp,
+                '<a title="Auto-link to Moodle Tracker" href="http://tracker.moodle.org/browse/MDL-$1">MDL-$1</a>',
                 $text);
 
         return $text;
