note 97349 modified in function.substr by danbrown

From: Date: Thu, 15 Apr 2010 12:53:50 +0000
Subject: note 97349 modified in function.substr by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-168268@lists.php.net to get a copy of this message
I had some problems with the order of the closing of tags. Example: <p>some <b><i>very</i>long</b> text to show my problem</p> would be converted to (if the script would cut the part after "very": <p>some <b><i>very</p></b></i> My second problem was, that the script didn't recognized tags like <a href="#" title="title"> So my version based on bennys and erez' work looks like this: <?php function mb_substrws($text, $length = 180) { if((mb_strlen($text) > $length)) { $whitespaceposition = mb_strpos($text, ' ', $length) - 1; if($whitespaceposition > 0) { $chars = count_chars(mb_substr($text, 0, ($whitespaceposition + 1)), 1); if ($chars[ord('<')] > $chars[ord('>')]) { $whitespaceposition = mb_strpos($text, ">", $whitespaceposition) - 1; } $text = mb_substr($text, 0, ($whitespaceposition + 1)); } // close unclosed html tags if(preg_match_all("|(<([\w]+)[^>]*>)|", $text, $aBuffer)) { if(!empty($aBuffer[1])) { preg_match_all("|</([a-zA-Z]+)>|", $text, $aBuffer2); if(count($aBuffer[2]) != count($aBuffer2[1])) { $closing_tags = array_diff($aBuffer[2], $aBuffer2[1]); $closing_tags = array_reverse($closing_tags); foreach($closing_tags as $tag) { $text .= '</'.$tag.'>'; } } } } } return $text; } ?> --was-- I had some problems with the order of the closing of tags. Example: <p>some <b><i>very</i>long</b> text to show my problem</p> would be converted to (if the script would cut the part after "very": <p>some <b><i>very</p></b></i> My second problem was, that the script didn't recognized tags like <a href="#" title="title"> So my version based on bennys and erez' work looks like this: <?php function mb_substrws($text, $length = 180) { if((mb_strlen($text) > $length)) { $whitespaceposition = mb_strpos($text, ' ', $length) - 1; if($whitespaceposition > 0) { $chars = count_chars(mb_substr($text, 0, ($whitespaceposition + 1)), 1); if ($chars[ord('<')] > $chars[ord('>')]) { $whitespaceposition = mb_strpos($text, ">", $whitespaceposition) - 1; } $text = mb_substr($text, 0, ($whitespaceposition + 1)); } // close unclosed html tags if(preg_match_all("|(<([\w]+)[^>]*>)|", $text, $aBuffer)) { if(!empty($aBuffer[1])) { preg_match_all("|</([a-zA-Z]+)>|", $text, $aBuffer2); if(count($aBuffer[2]) != count($aBuffer2[1])) { $closing_tags = array_diff($aBuffer[2], $aBuffer2[1]); $closing_tags = array_reverse($closing_tags); foreach($closing_tags as $tag) { $text .= '</'.$tag.'>'; } } } } } return $text; } http://php.net/manual/en/function.substr.php

« previous php.notes (#168268) next »