note 103687 added to function.wordwrap

From: Date: Thu, 28 Apr 2011 07:16:03 +0000
Subject: note 103687 added to function.wordwrap
Groups: php.notes 
Request: Send a blank email to php-notes+get-179220@lists.php.net to get a copy of this message
here is another function acts like wordwrap but ignores html tags. it basically takes out all the tags from the string, wordwrappes the string, then puts the tags back in. enjoy ;) <?php function html_wordwrap($str, $width = 75, $break = "\n", $cut = false) { //same functionality as wordwrap, but ignore html tags $unused_char = find_unused_char($str); //get a single character that is not used in the string $tags_arr = get_tags_array($str); $q = '?'; $str1 = ''; //the string to be wrapped (will not contain tags) $element_lengths = array(); //an array containing the string lengths of each element foreach($tags_arr as $tag_or_words) { if(preg_match("/<.*$q>/", $tag_or_words)) continue; $str1 .= $tag_or_words; $element_lengths[] = strlen($tag_or_words); } $str1 = wordwrap($str1, $width, $unused_char, $cut); foreach($tags_arr as &$tag_or_words) { if(preg_match("/<.*$q>/", $tag_or_words)) continue; $tag_or_words = substr($str1, 0, $element_lengths[0]); $str1 = substr($str1, $element_lengths[0]); array_shift($element_lengths); //delete the first array element - we have used it now so we do not need it } $str2 = implode('', $tags_arr); $str3 = str_replace($unused_char, $break, $str2); return $str3; } function get_tags_array($str) { //given a string, return a sequential array with html tags in their own elements $q = '?'; return preg_split("/(<.*$q>)/",$str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); } function find_unused_char($str) { //find an unused character in a string $possible_chars = array('|', '!', '@', '#', '$', '%', '^', '&', '*', '~'); foreach($possible_chars as $char) if(strpos($str, $char) === false) return $char; die('you must add another SINGLE unused character, not one of [|!@#$%^&*~], to the $possible_chars array in function find_unused_char'); } ?> ---- Server IP: 117.55.229.1 Probable Submitter: 150.101.100.168 ---- Manual Page -- http://www.php.net/manual/en/function.wordwrap.php Edit -- https://master.php.net/note/edit/103687 Del: integrated -- https://master.php.net/note/delete/103687/integrated Del: useless -- https://master.php.net/note/delete/103687/useless Del: bad code -- https://master.php.net/note/delete/103687/bad+code Del: spam -- https://master.php.net/note/delete/103687/spam Del: non-english -- https://master.php.net/note/delete/103687/non-english Del: in docs -- https://master.php.net/note/delete/103687/in+docs Del: other reasons-- https://master.php.net/note/delete/103687 Reject -- https://master.php.net/note/reject/103687 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#179220) next »