node_teaser
- Versions
- 4.6 – 5
node_teaser($body, $format = NULL)- 6
node_teaser($body, $format = NULL, $size = NULL)
Automatically generate a teaser for a node body in a given format.
Code
modules/node.module, line 150
<?php
function node_teaser($body, $format = NULL) {
$size = variable_get('teaser_length', 600);
// find where the delimiter is in the body
$delimiter = strpos($body, '<!--break-->');
// If the size is zero, and there is no delimiter, the entire body is the teaser.
if ($size == 0 && $delimiter === FALSE) {
return $body;
}
// If a valid delimiter has been specified, use it to chop off the teaser.
if ($delimiter !== FALSE) {
return substr($body, 0, $delimiter);
}
// We check for the presence of the PHP evaluator filter in the current
// format. If the body contains PHP code, we do not split it up to prevent
// parse errors.
if (isset($format)) {
$filters = filter_list_format($format);
if (isset($filters['filter/1']) && strpos($body, '<?') !== FALSE) {
return $body;
}
}
// If we have a short body, the entire body is the teaser.
if (strlen($body) < $size) {
return $body;
}
// The teaser may not be longer than maximum length specified. Initial slice.
$teaser = truncate_utf8($body, $size);
$position = 0;
// Cache the reverse of the teaser.
$reversed = strrev($teaser);
// In some cases, no delimiter has been specified. In this case, we try to
// split at paragraph boundaries.
$breakpoints = array('</p>' => 0, '<br />' => 6, '<br>' => 4, "\n" => 1);
// We use strpos on the reversed needle and haystack for speed.
foreach ($breakpoints as $point => $offset) {
$length = strpos($reversed, strrev($point));
if ($length !== FALSE) {
$position = - $length - $offset;
return ($position == 0) ? $teaser : substr($teaser, 0, $position);
}
}
// When even the first paragraph is too long, we try to split at the end of
// the last full sentence.
$breakpoints = array('. ' => 1, '! ' => 1, '? ' => 1, '。' => 0, '؟ ' => 1);
$min_length = strlen($reversed);
foreach ($breakpoints as $point => $offset) {
$length = strpos($reversed, strrev($point));
if ($length !== FALSE) {
$min_length = min($length, $min_length);
$position = 0 - $length - $offset;
}
}
return ($position == 0) ? $teaser : substr($teaser, 0, $position);
}
?>Login or register to post comments 