Trim text to a given length.
public static trimText ( string $str, integer $desiredLength, boolean $hellip = true, integer $cutOffCap = 10 ) : string | ||
$str | string | String to trim |
$desiredLength | integer | Target string length |
$hellip | boolean | Add dots when the string is too long |
$cutOffCap | integer | Maximum difference between string length when removing words |
return | string | Trimmed string |
/** * Get the excerpt of a given piece of text. * * @param int $length * @param bool $includeTitle * @param array|string|null $focus * * @return string|null */ public function getExcerpt($length = 200, $includeTitle = false, $focus = null) { $title = null; if ($includeTitle && $this->title !== null) { $title = Html::trimText(strip_tags($this->title), $length); $length = $length - strlen($title); } if ($this->body instanceof Content) { $this->body = $this->body->getValues(); } if (is_array($this->body)) { // Assume it's an array, strip some common fields that we don't need, implode the rest. $stripKeys = ['id', 'slug', 'datecreated', 'datechanged', 'username', 'ownerid', 'title', 'contenttype', 'status', 'taxonomy', 'templatefields']; foreach ($stripKeys as $key) { unset($this->body[$key]); } $excerpt = implode(' ', $this->body); } elseif (is_string($this->body) || is_object($this->body) && method_exists($this->body, '__toString')) { // otherwise we just use the string. $excerpt = (string) $this->body; } else { // Nope, got nothing. $excerpt = ''; } $excerpt = str_replace('>', '> ', $excerpt); if (empty($focus)) { $excerpt = Html::trimText(strip_tags($excerpt), $length); } else { $excerpt = $this->extractRelevant($focus, strip_tags($excerpt), $length); } if ($title !== null) { $excerpt = '<b>' . $title . '</b> ' . $excerpt; } return $excerpt; }
public function testTrimText() { // Simple text $input = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.'; $this->assertEquals('Lorem ipsum', Html::trimText($input, 11, false)); $this->assertEquals('Lorem ipsum…', Html::trimText($input, 12, true)); // Make sure tags are stripped $input = 'Lorem <strong>ipsum</strong> dolor sit amet, consectetur adipisicing elit.'; $this->assertEquals('Lorem ipsum', Html::trimText($input, 11, false)); }
public function testTrimText() { // Simple text $input = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.'; $this->assertEquals('Lorem ipsum', Html::trimText($input, 11, false)); $this->assertEquals('Lorem ipsum …', Html::trimText($input, 12, true)); // Make sure tags are stripped $input = 'Lorem <strong>ipsum</strong> dolor sit amet, consectetur adipisicing elit.'; $this->assertEquals('Lorem ipsum', Html::trimText($input, 11, false)); // Make sure long words (more than 10) are capped in the middle $input = 'I suffer from hippopotomonstrosesquipedaliophobia.'; $this->assertEquals('I suffer from hippopotomonstrosesquiped…', Html::trimText($input, 40, true)); }
/** * Creates RSS safe content. Wraps it in CDATA tags, strips style and * scripts out. Can optionally also return a (cleaned) excerpt. * * @param Content $record Bolt Content object * @param string $fields Comma separated list of fields to clean up * @param integer $excerptLength Number of chars of the excerpt * * @return string RSS safe string */ public function ampSafe($record, $fields = '', $excerptLength = 0) { // Make sure we have an array of fields. Even if it's only one. if (!is_array($fields)) { $fields = explode(',', $fields); } $fields = array_map('trim', $fields); $result = ''; foreach ($fields as $field) { if (!array_key_exists($field, $record->values)) { continue; } // Completely remove style and script blocks $maid = new Maid(['output-format' => 'html', 'allowed-tags' => ['a', 'b', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'p', 'strong', 'em', 'i', 'u', 'strike', 'ul', 'ol', 'li', 'img'], 'allowed-attribs' => ['id', 'class', 'name', 'value', 'href', 'src']]); $result .= $maid->clean($record->values[$field]); } if ($excerptLength > 0) { $result = Html::trimText($result, $excerptLength); } return new \Twig_Markup('<![CDATA[ ' . $result . ' ]]>', 'utf-8'); }
public function description($record = null) { $this->initialize($record); if (!empty($this->values['record']['description'])) { $description = $this->values['record']['description']; } else { if (!empty($this->values['inferred']['description'])) { $description = $this->values['inferred']['description']; } else { $description = $this->values['default']['description']; } } return Html::trimText(strip_tags($description), $this->config['description_length']); }
/** * Create an excerpt for the content. * * @param integer $length * @param boolean $includetitle * * @return \Twig_Markup */ public function getExcerpt($length = 200, $includetitle = false) { if ($includetitle) { $title = Html::trimText(strip_tags($this->getTitle()), $length); $length = $length - strlen($title); } if ($length > 0) { $excerptParts = []; if (!empty($this->contenttype['fields'])) { foreach ($this->contenttype['fields'] as $key => $field) { // Skip empty fields, and fields used as 'title'. if (!isset($this->values[$key]) || in_array($key, $this->getTitleColumnName())) { continue; } // add 'text', 'html' and 'textarea' fields. if (in_array($field['type'], ['text', 'html', 'textarea'])) { $excerptParts[] = $this->values[$key]; } // add 'markdown' field if ($field['type'] === 'markdown') { $excerptParts[] = $this->app['markdown']->text($this->values[$key]); } } } $excerpt = implode(' ', $excerptParts); $excerpt = Html::trimText(strip_tags($excerpt), $length); } else { $excerpt = ''; } if (!empty($title)) { $excerpt = '<b>' . $title . '</b> ' . $excerpt; } return new \Twig_Markup($excerpt, 'UTF-8'); }
/** * Get a unique URL for a record * * @param string $title * @param integer $id * @param string $contenttypeslug * @param boolean $fulluri * @param boolean $allowempty * @param boolean $slugfield * * @return string */ public function getUri($title, $id = 0, $contenttypeslug = "", $fulluri = true, $allowempty = true, $slugfield = 'slug') { $contenttype = $this->getContentType($contenttypeslug); $tablename = $this->getContenttypeTablename($contenttype); $id = intval($id); $slug = $this->app['slugify']->slugify($title); // Don't allow strictly numeric slugs. if (is_numeric($slug)) { $slug = $contenttype['singular_slug'] . "-" . $slug; } // Only add '{contenttype}/' if $full is requested. if ($fulluri) { $prefix = '/' . $contenttype['singular_slug'] . '/'; } else { $prefix = ''; } $fields = $this->getContentTypeFields($contenttypeslug); //check if the fieldname exists, otherwise use 'slug' as fallback if (!in_array($slugfield, $fields)) { $slugfield = 'slug'; } $query = sprintf("SELECT id from %s WHERE %s=? and id!=?", $tablename, $slugfield); $res = $this->app['db']->executeQuery($query, array($slug, $id), array(\PDO::PARAM_STR, \PDO::PARAM_INT))->fetch(); if (!$res) { $uri = $prefix . $slug; } else { for ($i = 1; $i <= 10; $i++) { $newslug = Html::trimText($slug, 127 - strlen($i), false) . '-' . $i; $res = $this->app['db']->executeQuery($query, array($newslug, $id), array(\PDO::PARAM_STR, \PDO::PARAM_INT))->fetch(); if (!$res) { $uri = $prefix . $newslug; break; } } // otherwise, just get a random slug. if (empty($uri)) { $suffix = '-' . $this->app['randomgenerator']->generateString(6, 'abcdefghijklmnopqrstuvwxyz01234567890'); $slug = Html::trimText($slug, 128 - strlen($suffix), false) . $suffix; $uri = $prefix . $slug; } } // When storing, we should never have an empty slug/URI. If we can't make a nice one, set it to 'slug-XXXX'. if (!$allowempty && empty($uri)) { $uri = 'slug-' . $this->app['randomgenerator']->generateString(6, 'abcdefghijklmnopqrstuvwxyz01234567890'); } return $uri; }
/** * Create an excerpt for the given content. * * @param \Bolt\Legacy\Content|array|string $content * @param integer $length Defaults to 200 characters * * @return string Resulting excerpt */ public function excerpt($content, $length = 200) { // If it's an content object, let the object handle it. if (is_object($content)) { if (method_exists($content, 'excerpt')) { return $content->excerpt($length); } else { $output = $content; } } elseif (is_array($content)) { // Assume it's an array, strip some common fields that we don't need, implode the rest. $stripKeys = ['id', 'slug', 'datecreated', 'datechanged', 'username', 'ownerid', 'title', 'contenttype', 'status', 'taxonomy']; foreach ($stripKeys as $key) { unset($content[$key]); } $output = implode(' ', $content); } elseif (is_string($content)) { // otherwise we just use the string. $output = $content; } else { // Nope, got nothing. $output = ''; } $output = str_replace('>', '> ', $output); $output = Html::trimText(strip_tags($output), $length); return $output; }
public function keywords($record = null) { $this->initialize($record); if (!empty($this->values['record']['keywords'])) { $keywords = $this->values['record']['keywords']; } else { if (!empty($this->values['inferred']['keywords'])) { $keywords = $this->values['inferred']['keywords']; } else { $keywords = $this->values['default']['keywords']; } } $keywords = str_replace(array("\r", "\n"), "", $keywords); return Html::trimText(strip_tags($keywords), $this->config['keywords_length']); }
/** * Get an array of safe (sanitised) function arguments from a trace entry. * * @param array $args * * @return array */ protected function getSafeArguments(array $args) { $argsSafe = []; foreach ($args as $arg) { $type = gettype($arg); switch ($type) { case 'string': $argsSafe[] = sprintf('<span>"%s"</span>', Html::trimText($arg, 30)); break; case 'integer': case 'float': $argsSafe[] = sprintf('<span>%s</span>', $arg); break; case 'object': $className = get_class($arg); $shortName = (new \ReflectionClass($arg))->getShortName(); $argsSafe[] = sprintf('<abbr title="%s">%s</abbr>', $className, $shortName); break; case 'boolean': $argsSafe[] = $arg ? '[true]' : '[false]'; break; default: $argsSafe[] = '[' . $type . ']'; } } return $argsSafe; }