note 89782 deleted from function.wordwrap by peehaa

From: Date: Thu, 09 Mar 2017 09:12:10 +0000
Subject: note 89782 deleted from function.wordwrap by peehaa
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-208879@lists.php.net to get a copy of this message
Note Submitter: r dot hartung at roberthartung dot de ---- I was wondering about my CMS to break up code but only non-HTML code - I didn't found anything so I came up with this little solution: <?php function wordWrapIgnoreHTML($string, $length = 45, $wrapString = "\n") { $wrapped = ''; $word = ''; $html = false; $string = (string) $string; for($i=0;$i<strlen($string);$i+=1) { $char = $string[$i]; /** HTML Begins */ if($char === '<') { if(!empty($word)) { $wrapped .= $word; $word = ''; } $html = true; $wrapped .= $char; } /** HTML ends */ elseif($char === '>') { $html = false; $wrapped .= $char; } /** If this is inside HTML -> append to the wrapped string */ elseif($html) { $wrapped .= $char; } /** Whitespace characted / new line */ elseif($char === ' ' || $char === "\t" || $char === "\n") { $wrapped .= $word.$char; $word = ''; } /** Check chars */ else { $word .= $char; if(strlen($word) > $length) { $wrapped .= $word.$wrapString; $word = ''; } } } if($word !== ''){ $wrapped .= $word; } return $wrapped; } $str = '<a href="http://www.example.de">'; $str .= 'Test-STRRRRRRRRRRRRRRRRRRIIIIIIIIIIIIIIIIIIIIIIING</a>'; $str .= '<!-- COMMENT_INSIDE_ANOTHER'; $str .= '_LONG_STRING //-->'; echo wordWrapIgnoreHTML($str, 25, '[BREAK]'); // Output: <a href="http://www.roberthartung.de"> // Test-STRRRRRRRRRRRRRRRRRRI[BREAK] // IIIIIIIIIIIIIIIIIIIIIING // </a><!-- ... //--> ?> [NOTE BY danbrown AT php DOT net: Contains a bug fix provided by (jaw AT condidact DOT dk) on 02-APR-09 to address an issue where "the last word in a non-html-wrapped string will be omitted."]

« previous php.notes (#208879) next »