Schnellzugriff » 
Home 
« suPHP und PHP Opcode Caches Debian Lenny: pam_mount, files and loop devices »

TYPO3 HTML save cropping

Meistens reicht die Methode tslib_cObj::crop vollkommen aus, um Texte – etwa für eine Listenansicht – zu kürzen. Wenn jedoch RTE formatierte Texte im Spiel sind und die Formatierung in der gekürzten Version beibehalten werden soll, ist es reine Glückssache, kein invalides (X)HTML durch nicht geschlossene bzw. “verkrüppelte” Tags zu generieren. Abhilfe schafft die folgende crop-Methode, die eine Portierung der Javascript-Version von Steven Levithan darstellt:

public static function crop($input, $numMaxChars) {
	$output = '';
	$charCount = 0;
	$openTags = array();
	$matches = array();
	$htmlTags = '/\w+|[^\w<]|<(\/)?(\w+)[^>]*(\/)?>|</';
	$selfClosingHtmlTags = '/^(?:[hb]r|img)$/i';

	preg_match_all($htmlTags, $input, $matches);
	$i = 0;
	$numMatches = count($matches[0]);
	while(($i < $numMatches) && ($charCount < $numMaxChars)) {
		// are we dealing with an html tag?
		if($matches[2][$i] != '') {
			$output .= $matches[0][$i];
			// if it isn't a self closing tag
			if(preg_match($selfClosingHtmlTags, $matches[2][$i]) == 0) {
				// if its a closing tag...
				if($matches[1][$i] == '/') {
					array_pop($openTags);
				} else {
					$openTags[] = $matches[2][$i];
				}
			}
		} else {
			$charCount += mb_strlen($matches[0][$i], $GLOBALS['TSFE']->renderCharset);
			if($charCount <= $numMaxChars) {
				$output .= $matches[0][$i];
			}
		}

		$i++;
	}

	// closing open tags
	$i = count($openTags);
	while($i--) {
		$output .= '</' . $openTags[$i] . '>';
	}

	return $output;
}

Dienstag, März 16th, 2010 and is filed under PHP, Programmierung, TYPO3. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.


© 2007 - 2009 Thorsten Boock