<?php
/*
Plugin Name: wptexturize bugfix
Plugin URI: http://blog.fxposter.org/2008/05/19/wptexturize-bugfix-plugin/
Description: Fix for a default wptexturize filter bug
Author: Pavel Forkert
Version: 0.1
Author URI: http://blog.fxposter.org/
*/

function wptexturize_bugfix($text) {
  global 
$wp_cockneyreplace;
  
$next true;
  
$output '';
  
$curl '';
  
$textarr preg_split('/(<.*>|\[.*\])/Us'$text, -1PREG_SPLIT_DELIM_CAPTURE);
  
$stop count($textarr);

  
// if a plugin has provided an autocorrect array, use it
  
if ( isset($wp_cockneyreplace) ) {
    
$cockney array_keys($wp_cockneyreplace);
    
$cockneyreplace array_values($wp_cockneyreplace);
  } else {
    
$cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
    
$cockneyreplace = array("&#8217;tain&#8217;t","&#8217;twere","&#8217;twas","&#8217;tis","&#8217;twill","&#8217;til","&#8217;bout","&#8217;nuff","&#8217;round","&#8217;cause");
  }

  
$static_characters array_merge(array('---'' -- ''--''xn&#8211;''...''``''\'s''\'\''' (tm)'), $cockney);
  
$static_replacements array_merge(array('&#8212;'' &#8212; ''&#8211;''xn--''&#8230;''&#8220;''&#8217;s''&#8221;'' &#8482;'), $cockneyreplace);

  
$dynamic_characters = array('/\'(\d\d(?:&#8217;|\')?s)/''/(\s|\A|")\'/''/(\d+)"/''/(\d+)\'/''/(\S)\'([^\'\s])/''/(\s|\A)"(?!\s)/''/"(\s|\S|\Z)/''/\'([\s.]|\Z)/''/(\d+)x(\d+)/');
  
$dynamic_replacements = array('&#8217;$1','$1&#8216;''$1&#8243;''$1&#8242;''$1&#8217;$2''$1&#8220;$2''&#8221;$1''&#8217;$1''$1&#215;$2');

  
$tag_list = array();
  for ( 
$i 0$i $stop$i++ ) {
    
$curl $textarr[$i];

    if (isset(
$curl{0}) && '<' != $curl{0} && '[' != $curl{0} && $next) { // If it's not a tag
      // static strings
      
$curl str_replace($static_characters$static_replacements$curl);
      
// regular expressions
      
$curl preg_replace($dynamic_characters$dynamic_replacements$curl);
    } elseif (
strpos($curl'<code') !== false || strpos($curl'<pre') !== false || strpos($curl'<kbd') !== false || strpos($curl'<style') !== false || strpos($curl'<script') !== false) {
      
$next false;
      
preg_match('/<([a-z]+)/i'$curl$tag);
      
$tag_list[] = '</' $tag[1];
    } elseif(
count($tag_list) == 0) {
      
$next true;
    } elseif (
strpos($curlend($tag_list)) !== false) {
      
$next true;
      
array_pop($tag_list);
    }

    
$curl preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/''&#038;$1'$curl);
    
$output .= $curl;
  }

  return 
$output;
}

remove_filter('the_content''wptexturize');
add_filter('the_content''wptexturize_bugfix');