Discussions » Greasy Fork Feedback

Test of code blocks on the forum

§
Posted: 2015-04-21
Edited: 2015-04-21

Test of code blocks on the forum

I'm testing out a patch that should stop content in <code> blocks (including Markdown backticks) from getting things like @mentions and #hashtags linkified.

@mention

#hashtag

See if you can break it!

§
Posted: 2015-04-21

/me also found this feature

§
Posted: 2015-04-21

Here's the code, BTW:

   /** Do a preg_replace, but don't affect things inside <code> tags.
    * The three parameters are identical to the ones you'd pass
    * preg_replace.
    *
    * @param mixed $Pattern
    * @param mixed $Replacement
    * @param mixed $Subject
    * @return string
    */
   public static function ReplaceProtectCodeBlocks($Pattern, $Replacement, $Subject) {
     // Take the code blocks out, replace with something unlikely to
     // appear in the string, and keep track of what substring got
     // replaced with what code.
     $Replacements = array();
     $Subject = preg_replace_callback(
       '/<code>.*?<\/code>/i',
       function($Matches) use (&$Replacements) {
         // Random string and replacement index, surrounded by
         // whitespace to try to prevent the characters from being
         // picked up by $Pattern.
         $ReplacementString = ' 5z9Ah9Y2sX5xnzUx8wSq'.count($Replacements).' ';
         $Replacements[$ReplacementString] = $Matches[0];
         return $ReplacementString;
       },
       $Subject
     );


     // Do the requested replacement.
     $Subject = preg_replace($Pattern, $Replacement, $Subject);

     // Put back the code blocks. First in, last out so that e.g.
     // random10 is not replaced by random1.
     foreach (array_reverse($Replacements) as $Placeholder => $Original) {
       $Subject = str_replace($Placeholder, $Original, $Subject);
     }

     return $Subject;
   }
§
Posted: 2015-04-21

/me think this is great.

Post reply

Sign in to post a reply.