Truncates a text.

@param string $text    The text to truncate
@param array  $options Truncation options. Can be 'length'=>integer, 'read_more'=>boolean,
'ending'=>string, 'exact'=>boolean, 'consider_html'=>false

@return string
557193
public function truncate($text, $options = array())
    {
        $default = array('length' => 300, 'read_more' => false, 'ending' => '...', 'exact' => true, 'consider_html' => false);

        $options = array_merge($default, $options);

        extract($options, EXTR_SKIP);

        if ($consider_html) {
            // if the plain text is shorter than the maximum length, return the whole text
            if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
                return $text;
            }

            // splits all html-tags to scanable lines
            preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);

            $total_length = strlen($ending);
            $open_tags = array();
            $truncate = '';

            foreach ($lines as $line_matchings) {
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
                if (!empty($line_matchings[1])) {
                    // if it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>)
                    if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
                        // do nothing
                    // if tag is a closing tag (f.e. </b>)
                    } elseif (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
                        // delete tag from $open_tags list
                        $pos = array_search($tag_matchings[1], $open_tags);
                        if ($pos !== false) {
                            unset($open_tags[$pos]);
                        }
                    // if tag is an opening tag (f.e. <b>)
                    } elseif (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
                        // add tag to the beginning of $open_tags list
                        array_unshift($open_tags, strtolower($tag_matchings[1]));
                    }
                    // add html-tag to $truncate'd text
                    $truncate .= $line_matchings[1];
                }

                // calculate the length of the plain text part of the line; handle entities as one character
                $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
                if ($total_length + $content_length > $length) {
                    // the number of characters which are left
                    $left = $length - $total_length;
                    $entities_length = 0;
                    // search for html entities
                    if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
                        // calculate the real length of all entities in the legal range
                        foreach ($entities[0] as $entity) {
                            if ($entity[1] + 1 - $entities_length <= $left) {
                                --$left;
                                $entities_length += strlen($entity[0]);
                            } else {
                                // no more characters left
                                break;
                            }
                        }
                    }
                    $truncate .= AnHelperString::substr($line_matchings[2], 0, $left + $entities_length);
                    // maximum lenght is reached, so get off the loop
                    break;
                } else {
                    $truncate .= $line_matchings[2];
                    $total_length += $content_length;
                }

                // if the maximum length is reached, get off the loop
                if ($total_length >= $length) {
                    break;
                }
            }
        } else {
            if (strlen($text) <= $length) {
                return $text;
            } else {
                $truncate = AnHelperString::substr($text, 0, $length - strlen($ending));
            }
        }

        // if the words shouldn't be cut in the middle...
        if (!$exact) {
            // ...search the last occurance of a space...
            $spacepos = strrpos($truncate, ' ');
            if (isset($spacepos)) {
                // ...and cut the text in this position
                $truncate = AnHelperString::substr($truncate, 0, $spacepos);
            }
        }

        // add the defined ending to the text
        $truncate .= $ending;

        if ($consider_html) {
            // close all unclosed html-tags
            foreach ($open_tags as $tag) {
                $truncate .= '</'.$tag.'>';
            }
        }

        if ($read_more) {
            $short_id = uniqid();
            $full_id = uniqid();
            $read_more = ' <a class="an-read-more" data-trigger="ReadMore" data-short="'.$short_id.'" data-full="'.$full_id.'" href="#">'.AnTranslator::_('LIB-AN-READMORE').'</a>';
            $read_less = ' <a class="an-read-less" data-trigger="ReadLess" data-short="'.$short_id.'" data-full="'.$full_id.'" href="#">'.AnTranslator::_('LIB-AN-READLESS').'</a>';
            $truncate = '<div id="'.$short_id.'">'.$truncate.$read_more.'</div>';
            $truncate .= '<div id="'.$full_id.'" class="hide">'.$text.$read_less.'</div>';
        }

        return $truncate;
    }
836014
public function truncate(int $maximum) : Text
    {
        return $this->pipe(
            function (string $value) use ($maximum) : string {
                return strlen($value) > $maximum
                    ? substr($value, 0, $maximum)
                    : $value;
            }
        );
    }
685034
def truncate(string, width, options={})
      trailing = options[:trailing] || '…'

      chars = string.to_s.chars.to_a
      if chars.length < width && chars.length > 3
        chars.join
      elsif chars.length > 3
        (chars[0, width - trailing.length].join) + trailing
      end
    end
154169
public static function normalizeText($text)
    {
        $text = strtolower($text);
        $text = preg_replace('/[^a-z0-9 -]/im', ' ', $text);
        $text = preg_replace('/( +)/im', ' ', $text);

        return trim($text);
    }
352711
public function sentimentClassify($text, $options=array()){

        $data = array();
        
        $data['text'] = $text;

        $data = array_merge($data, $options);
        $data = mb_convert_encoding(json_encode($data), 'GBK', 'UTF8');

        return $this->request($this->sentimentClassifyUrl, $data);
    }
1327612
def trunc(text, length):
    
    if length < 1:
        raise ValueError("length should be 1 or larger")

    # Remove whitespace first so no unneccesary truncation is done.
    text = text.strip()
    text_length = wcswidth(text)

    if text_length <= length:
        return text

    # We cannot just remove n characters from the end since we don't know how
    # wide these characters are and how it will affect text length.
    # Use wcwidth to determine how many characters need to be truncated.
    chars_to_truncate = 0
    trunc_length = 0
    for char in reversed(text):
        chars_to_truncate += 1
        trunc_length += wcwidth(char)
        if text_length - trunc_length <= length:
            break

    # Additional char to make room for elipsis
    n = chars_to_truncate + 1
    return text[:-n].strip() + '…'
1311613
public function truncate($length)
    {
        $this->_text = StringHelper::truncate($this->_text, $length);
        
        return $this;
    }
611344
public function write($text, $option = [])
    {
        Output::write($this->format($text, $option));
        return $this;
    }
1368671
public function disabledLink($text, array $options = []) {
		$defaults = ['class' => 'disabledLink', 'title' => __d('tools', 'notAvailable')];
		$options += $defaults;

		return $this->Html->tag('span', $text, $options);
	}
624383
public static function cut(string $text, int $start = 0, int $end = 0)
    {
        return Str::sub($text, $start, $end);
    }
1198873
public function image($text, array $options = []) {
		return $this->Html->image($this->uri($text), $options);
	}
952876
public function apply($text)
    {
        $setCodes = array();
        $unsetCodes = array();
        if (null !== $this->foreground) {
            $setCodes[] = $this->foreground['set'];
            $unsetCodes[] = $this->foreground['unset'];
        }
        if (null !== $this->background) {
            $setCodes[] = $this->background['set'];
            $unsetCodes[] = $this->background['unset'];
        }
        if (count($this->options)) {
            foreach ($this->options as $option) {
                $setCodes[] = $option['set'];
                $unsetCodes[] = $option['unset'];
            }
        }
        if (0 === count($setCodes)) {
            return $text;
        }
        return sprintf("\033[%sm%s\033[%sm", implode(';', $setCodes), $text, implode(';', $unsetCodes));
    }
275081
protected static function _removeLastWord($text)
    {
        $spacepos = mb_strrpos($text, ' ');

        if ($spacepos !== false) {
            $lastWord = mb_strrpos($text, $spacepos);

            // Some languages are written without word separation.
            // We recognize a string as a word if it doesn't contain any full-width characters.
            if (mb_strwidth($lastWord) === mb_strlen($lastWord)) {
                $text = mb_substr($text, 0, $spacepos);
            }

            return $text;
        }

        return '';
    }
482404
static public function foldAny( $text )
    {
        // Don't fold unless we have to.
        if ( strlen( $text ) <= self::$limit )
        {
            return $text;
        }

        // go to 998'th char.
        // search back to whitespace
        // fold

        $length = strlen( $text );
        $folded = "";
        // find first occurence of whitespace searching backwards
        $search = 0;
        $previousFold = 0;

        while ( ( $search + self::$limit ) < $length )
        {
            // search from the max possible length of the substring
            $search += self::$limit;
            while ( $text[$search] != " " && $text[$search] != "\t" && $search > $previousFold )
            {
                $search--;
            }

            if ( $search == $previousFold )
            {
                // continuous string of more than limit chars.
                // We will just have to continue searching forwards to the next whitespace instead
                // This is not confirming to standard.. but what can we do?
                $search += self::$limit; // back to where we started
                while ( $search < $length && $text[$search] != " " && $text[$search] != "\t" )
                {
                    $search++;
                }
            }

            // lets fold
            if ( $folded === "" )
            {
                $folded = substr( $text, $previousFold, $search - $previousFold );
            }
            else
            {
                $folded .= ezcMailTools::lineBreak() .
                           substr( $text, $previousFold, $search - $previousFold );
            }
            $previousFold = $search;
        }
        // we need to append the rest if there is any
        if ( $search < $length )
        {
            $folded .= ezcMailTools::lineBreak() . substr( $text, $search );
        }
        return $folded;
    }
1278009
public static function shorten($text, $maxlength = 140, $end = '[...]') {
        $maxlength++;
        if (mb_strlen($text) > $maxlength) {
            $subex = mb_substr($text, 0, $maxlength - 5);
            $exwords = explode(' ', $subex);
            $excut = - (mb_strlen($exwords[count($exwords)-1]));
            if ($excut < 0) {
                $text = mb_substr($subex, 0, $excut);
            } else {
                $text = $subex;
            }
            $text .= $end;
        }
        return $text;
    }
930001
public function colorize($text, $options = 0, $width = 0)
    {
        $map = [
            self::AT_BOLD => "\033[1m",
            self::AT_ITALICS => "\033[3m",
            self::AT_UNDERLINE => "\033[4m",
            self::AT_BLINK => "\033[5m",
            self::AT_INVERSE => "\033[7m",

            self::BC_BLACK => "\033[40m",
            self::BC_RED => "\033[41m",
            self::BC_GREEN => "\033[42m",
            self::BC_YELLOW => "\033[43m",
            self::BC_BLUE => "\033[44m",
            self::BC_MAGENTA => "\033[45m",
            self::BC_CYAN => "\033[46m",
            self::BC_WHITE => "\033[47m",

            self::FC_BLACK => "\033[30m",
            self::FC_RED => "\033[31m",
            self::FC_GREEN => "\033[32m",
            self::FC_YELLOW => "\033[33m",
            self::FC_BLUE => "\033[34m",
            self::FC_MAGENTA => "\033[35m",
            self::FC_CYAN => "\033[36m",
            self::FC_WHITE => "\033[37m",
        ];

        if (!$this->isSupportColor()) {
            return $width ? str_pad($text, $width) : $text;
        }

        $c = '';
        for ($i = 0; $i < 32; $i++) {
            if ((1 << $i) & $options) {
                $c .= $map[(1 << $i) & $options];
            }
        }

        return $c . $text . "\033[0m" . str_repeat(' ', max($width - strlen($text), 0));
    }
5861
public function clean($text)
    {
        $len = $this->utf8 ? mb_strlen($text) : strlen($text);

        if ($len <= $this->max) {
            return $text;
        }

        return $this->utf8 ? mb_substr($text, 0, $this->max) : substr($text, 0, $this->max);
    }