note 90724 modified in function.substr by thiago

From: Date: Wed, 06 May 2009 12:20:53 +0000
Subject: note 90724 modified in function.substr by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-154280@lists.php.net to get a copy of this message
If you need a word-sensitive and also html-tags aware version of substr, this one should do the job. It works fine for me <?php /** * word-sensitive substring function with html tags awareness * @param text The text to cut * @param len The maximum length of the cut string * @returns string **/ function substrws( $text, $len=180 ) { if( (strlen($text) > $len) ) { $whitespaceposition = strpos($text," ",$len)-1; if( $whitespaceposition > 0 ) $text = substr($text, 0, ($whitespaceposition+1)); // close unclosed html tags if( preg_match_all("|<([a-zA-Z]+)>|",$text,$aBuffer) ) { if( !empty($aBuffer[1]) ) { preg_match_all("|</([a-zA-Z]+)>|",$text,$aBuffer2); if( count($aBuffer[1]) != count($aBuffer2[1]) ) { foreach( $aBuffer[1] as $index => $tag ) { if( empty($aBuffer2[1][$index]) || $aBuffer2[1][$index] != $tag) $text .= '</'.$tag.'>'; } } } } } return $text; } ?> --was-- If you need a word-sensitive and also html-tags aware version of substr, this one should do the job. It works fine for me /** * word-sensitive substring function with html tags awareness * @param text The text to cut * @param len The maximum length of the cut string * @returns string **/ function substrws( $text, $len=180 ) { if( (strlen($text) > $len) ) { $whitespaceposition = strpos($text," ",$len)-1; if( $whitespaceposition > 0 ) $text = substr($text, 0, ($whitespaceposition+1)); // close unclosed html tags if( preg_match_all("|<([a-zA-Z]+)>|",$text,$aBuffer) ) { if( !empty($aBuffer[1]) ) { preg_match_all("|</([a-zA-Z]+)>|",$text,$aBuffer2); if( count($aBuffer[1]) != count($aBuffer2[1]) ) { foreach( $aBuffer[1] as $index => $tag ) { if( empty($aBuffer2[1][$index]) || $aBuffer2[1][$index] != $tag) $text .= '</'.$tag.'>'; } } } } } return $text; } http://php.net/manual/en/function.substr.php

« previous php.notes (#154280) next »