Have a Snippet?

Keep, track and share your code snippets with your friends

PHP: Symfony1.4: use Tidy to create announces from blob field Share on Vkontakte

usage:rn$announce = ccTidy::clearAndCrop($content, $extractLen = 100, $raw = true);

/**
 * Description of ccTidyclass
 */
class ccTidy {
  
  /**
   * Get part of HTML, clear all tags and crop substring
   * 
   * @param string $content
   * @param integer $extractLen = 100
   * @param boolean $raw
   * @return string $subContent cleared and croped
   */
  public static function clearAndCrop($content, $extractLen = 100, $raw = true)
  {
    /*
     * Available options:
     * 'drop-proprietary-attributes' => true,
     * 'clean'           => true,
     * 'wrap-attributes' => true,
     * 'wrap'            => 200
     */
    $config = array(
      'indent'          => true,
      'output-xhtml'    => false,
      'drop-font-tags'  => true,
    );

    $tidy = new tidy;
    $tidy->parseString($content, $config, 'UTF8');
    $tidy->CleanRepair();
    
    $tidy = strip_tags($tidy);
    $extractLen = ($extractLen > mb_strlen($tidy, 'utf-8') ? mb_strlen($tidy, 'utf-8') : $extractLen );
    // kill massive spaces
    $tidy = preg_replace('/(\s)+/', ' ', $tidy);
    $tidy = trim($tidy);

    if (strpos($tidy, ' ') != 0)
    {
      /*
       * отсчитаем 100 букв и найдем ближайший пробел
       */
      $cutPos     = @mb_strpos($tidy, ' ' , $extractLen, 'utf-8');
      $subContent = @mb_substr($tidy, 0, ($cutPos ? $cutPos : $extractLen), 'utf-8');
    }
    else
    {
      $subContent = mb_substr($tidy, 0, $extractLen, 'utf-8');
      /*
       * т.к. в тексте нет пробелов поставим мягкие побелы
       */
      /*
       * TODO: fix load helper
       */
//      sfLoader::loadHelpers('LongWord');
//      $subContent = brakeLongWords($subContent);
    }

    $subContent .= ($extractLen < mb_strlen($tidy, 'utf-8') ? '...' : '' );

    if ($raw) {
      return $subContent;
    } else {
      return ''.$subContent.'';
    }
  }
}


Tag: PHP, Tidy, Helper

0 Comments