note 120007 added to function.wordwrap
| From: | simbiat at bk dot ru | Date: | Sat, 08 Oct 2016 09:41:20 +0000 |
| Subject: | note 120007 added to function.wordwrap | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-206805@lists.php.net to get a copy of this message | ||
Some people use wordwrap as long text cutter. I have a slightly different approach for that. The
function does not wrap the text, but returns the position where to cut. It preserves HTML tags (does
not count them) and strips br tags and whitespaces at the end. I am looking into a way prevent HTML
tags corruption which can happen at this time and also support BB tags like code and quote, so that
they won't be counted as well. When I do, I'll post an updated version of the code.
<?php
function txtcut($string, $length) {
$tag = false;
$chars = 0;
$position = 0;
$split = str_split($string);
foreach ($split as $char) {
$position++;
if ($char == "<") {
$tag = true;
continue;
}
if ($char == ">") {
$tag = false;
continue;
}
if ($tag == true) {
continue;
}
$chars++;
if ($chars >= $length) {
if ($char == " " || $char == "\r" || $char == "\n") {
$position--;
break;
}
}
}
if ($position == strlen($string)) {
return strlen($string);
} else {
$string = substr($string, 0, $position);
if (substr($string, -4, 4) == "<br>") {
$string = rtrim(substr($string, 0, -4));
}
return strlen($string);
}
}
?>
----
Server IP: 72.52.91.14
Probable Submitter: 109.173.40.126
----
Manual Page -- http://php.net/manual/en/function.wordwrap.php
Edit -- https://master.php.net/note/edit/120007
Del: integrated -- https://master.php.net/note/delete/120007/integrated
Del: useless -- https://master.php.net/note/delete/120007/useless
Del: bad code -- https://master.php.net/note/delete/120007/bad+code
Del: spam -- https://master.php.net/note/delete/120007/spam
Del: non-english -- https://master.php.net/note/delete/120007/non-english
Del: in docs -- https://master.php.net/note/delete/120007/in+docs
Del: other reasons-- https://master.php.net/note/delete/120007
Reject -- https://master.php.net/note/reject/120007
Search -- https://master.php.net/manage/user-notes.php