note 90724 deleted from function.substr by peehaa
| From: | peehaa@php.net | Date: | Mon, 28 Nov 2016 19:44:52 +0000 |
| Subject: | note 90724 deleted from function.substr by peehaa | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-207715@lists.php.net to get a copy of this message | ||
Note Submitter: benny at bennyborn dot de
----
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;
}
?>