Get text trimmed to the nearest word.

@param string $text 		 The text to trim.
@param int    $char_limit The maximum chars to allow.
@return string
486915
public static function trim_to_nearest_word( $text, $char_limit ) {
		if ( strlen( $text ) <= $char_limit ) {
			return $text;
		}

		$wrapped_text = explode( '\n', wordwrap( $text , $char_limit, '\n' ) );

		return is_array( $wrapped_text ) ? $wrapped_text[0] : substr( $text, 0, $char_limit );
	}
329252
public function getLimitedContent( $limit = CoreGlobal::DISPLAY_TEXT_MEDIUM ) {

		$content = $this->content;

		if( strlen( $content ) > $limit ) {

			$content = substr( $content, 0, $limit );
		}

		return HtmlPurifier::process( $content );
	}
1085048
public function process($text)
    {
        $iterations = $this->maxIterations === null ? 1 : $this->maxIterations;
        $context = new ProcessorContext();
        $context->processor = $this;

        while ($iterations--) {
            $context->iterationNumber++;
            $newText = $this->processIteration($text, $context, null);
            if ($newText === $text) {
                break;
            }
            $text = $newText;
            $iterations += $this->maxIterations === null ? 1 : 0;
        }

        return $text;
    }
1185844
private static function trimEdge($string, $char)
    {
        if (substr($string, 0, 1) == $char) {
            $string = substr($string, 1, -1);
        }

        return $string;
    }
431082
public function getKeyword($text)
    {
        $found = null;
        $text = trim($text);
        $iText = strtoupper(TextNormalizer::stripDiacritics($text));
        foreach ($this->keywords as $keyword) {
            /** @var Keyword $keyword */
            $tmpText = trim($keyword->getText());
            if ($tmpText === $text
                || (
                    empty($keyword->isCaseSensitive()) &&
                    strtoupper(TextNormalizer::stripDiacritics($tmpText)) === $iText)
            ) {
                $found = $keyword;
                break;
            }
        }

        return $found;
    }
554851
public static function getWordsWithinCharLimit($sentence, $limit = 150) {
        $str = '';
        $i = 1;

        if(strlen($sentence) < $limit) {
            return $sentence;
        }

        while (strlen($current = self::getWords($sentence, $i++)) < $limit) {
            $str = $current;
        }

        return $str;
    }
1070990
protected function segmentLine($text)
    {
        list($lines, $temp, $width) = [[], '', 0];

        foreach (preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY) as $word) {
            if ($width + mb_strwidth($word) > 48) {
                $lines[] = $temp;
                $temp = '';
                $width = 0;
            }

            $temp .= $word;
            $width += mb_strwidth($word);
        }

        $lines[] = $temp;

        return implode(PHP_EOL, $lines);
    }
15016
public static function limitWords(string $string, int $words = 100, string $sufix = '...'): string
	{
		preg_match('/^\s*+(?:\S++\s*+){1,' . $words . '}/', $string, $matches);

		if(isset($matches[0]) && mb_strlen($matches[0]) < mb_strlen($string))
		{
			return trim($matches[0]) . $sufix;
		}

		return $string;
	}
1355323
public static function urlizeTrim($text, $separator = '-')
    {
        return trim(self::urlize(UtilString::toSlugg($text), $separator), $separator);
    }
573250
public function truncateHtmlText($text, $characters = 300)
    {
        // Clean up html tags and special characters
        $text = preg_replace('/<[^>]*>/', ' ', $text);
        $text = str_replace("\r", '', $text); // replace with empty space
        $text = str_replace("\n", ' ', $text); // replace with space
        $text = str_replace("\t", ' ', $text); // replace with space
        $text = preg_replace('/\s+/', ' ', $text); // remove multiple consecutive spaces
        $text = preg_replace('/^[\s]/', '', $text); // Remove leading space from excerpt
        $text = preg_replace('/[\s]$/', '', $text); // Remove trailing space from excerpt

        // If we are already within the limit, just return the text
        if (mb_strlen($text) <= $characters) {
            return $text;
        }

        // Truncate to character limit if longer than requested
        $text = substr($text, 0, $characters);

        // We don't want the string cut mid-word, so search for the last space and trim there
        $lastSpacePosition = strrpos($text, ' ');
        if (isset($lastSpacePosition)) {
            // Cut the text at this last word
            $text = substr($text, 0, $lastSpacePosition);
        }

        return $text;
    }
1138650
public static function text($chars, $min, $max)
    {
        $length = mt_rand($min, $max);
        $charLength = mb_strlen($chars);
        $result = '';
        for($i = 0; $i < $length; ++$i)
        {
            $result .= mb_substr($chars, mt_rand(1, $charLength) - 1, 1);
        }
        return $result;
    }
1122221
public function parse(string $text) : \stdClass
    {
        $items = Text::split($text, $this->separator);
        $itemsCount = count($items);
        $itemIndex = 0;
        $names = array_keys($this->fields);
        $namesCount = count($names);
        $nameIndex = 0;
        $index = 0;
        $separatorLength = strlen($this->separator);
        $itemsLeft = false;
        $this->clearValues();
        try {
            while ($itemIndex < $itemsCount && $nameIndex < $namesCount) {
                $syntax = $this->fields[$names[$nameIndex]];
                $this->values[$names[$nameIndex]]->value = $syntax->parse($items[$itemIndex]);
                $this->values[$names[$nameIndex]]->error = null;
                $index += strlen($items[$itemIndex]) + $separatorLength;
                $nameIndex ++;
                $itemIndex ++;
                if ($syntax instanceof OptionalSyntax && !$syntax->success()) {
                    $itemIndex --;
                }
            }
            // if items are left
            if ($itemIndex < $itemsCount)
                $itemsLeft = true;
            // if fields are left
            while ($nameIndex < $namesCount) {
                $syntax = $this->fields[$names[$nameIndex]];
                $this->values[$names[$nameIndex]]->value = $syntax->parse('');
                $this->values[$names[$nameIndex]]->error = null;
                $nameIndex ++;
            }
        } catch (ParseException $e) {
            if ($itemIndex < $itemsCount) {
                $this->values[$names[$nameIndex]]->error = static::INVALID_FIELD;
                $error = "Unable to parse the item '{$items[$itemIndex]}' for field '{$names[$nameIndex]}'";
                $extra = [
                    'type'  => 'invalid-field',
                    'field' => $names[$nameIndex],
                    'text'  => $items[$itemIndex]
                ];
            } else {
                $this->values[$names[$nameIndex]]->error = static::MISSING_FIELD;
                $error = "No item left for field '{$names[$nameIndex]}'";
                $extra = [
                    'type'  => 'missing-field',
                    'field' => $names[$nameIndex],
                    'position' => $e->position()
                ];
            }
            throw new ParseException($this, $text, $index + $e->position(), $error, $extra, $e);
        }

        if ($itemsLeft) {
            $extra = [
                'type'  => 'additional-items',
                'items' => array_slice($items, $itemIndex)
            ];
            throw new ParseException($this, $text, $index - $separatorLength,
                "Additional items with no corresponding fields", $extra);
        }

        return (object) array_map(function(\stdClass $field) {
            return $field->value;
        }, $this->values);
    }
178128
public function getStringWidth(string $text): float
    {
        $style = $this->getStyle($this->currentStyle);

        return mb_strlen($text) * ($style['size'] / 2);
    }
1132628
public static function clearText(string $text = null) : string
    {
        if (is_null($text)){
            return '';
        }
        return strip_tags(trim($text));
    }
1233149
public function getMessageLines($text)
    {
        $message = $text;
        $wrapLength = 40;
        // wrap the message to max chars
        $message = wordwrap($message, $wrapLength - 2);
        // split into array of lines
        return explode("\n", $message);
    }
879997
static private function leetify( $text )
    {
        $searchMap = array( '/to/i', '/for/i', '/ate/i', '/your/i', '/you/i', '/l/i', '/e/i', '/o/i', '/a/i', '/t/i' );
        $replaceMap = array( '2', '4', '8', 'ur', 'u', '1', '3', '0', '4', '7' );

        $textBlocks = preg_split( '/(%[^ ]+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
        $newTextBlocks = array();
        foreach ( $textBlocks as $text )
        {
            if ( strlen( $text ) && $text[0] == '%' )
            {
                $newTextBlocks[] = (string) $text;
                continue;
            }
            $text = preg_replace( $searchMap, $replaceMap, $text );

            $newTextBlocks[] = (string) $text;
        }
        $text = implode( '', $newTextBlocks );
        return $text;
    }
1351415
public function trim($string, $charlist = null)
    {
        $string = (string)$string;

        if ($charlist === null) {
            return trim($string);
        } else {
            return trim($string, $charlist);
        }
    }