Попробуйте что-то вроде этого:
<?php
//somehow your $text string is set
if(strlen($text) > 50) {
//this finds the position of the first period after 50 characters
$period = strpos($text, '.', 50);
//this gets the characters 0 to the period and stores it in $teaser
$teaser = substr($text, 0, $period);
}
Давайте обновим его, чтобы иметь более безопасный код, благодаря @ Michael_Rose
<?php
//somehow your $text string is set
$teaser = $text;
if(mb_strlen($text) > 50) {
//this finds the position of the first period after 50 characters
$period = strpos($text, '.', 50);
//this finds the position of the first space after 50 characters
//we can use this for a clean break if a '.' isn't found.
$space = strpos($text, ' ', 50);
if($period !== false) {
//this gets the characters 0 to the period and stores it in $teaser
$teaser = substr($text, 0, $period);
} elseif($space !== false) {
//this gets the characters 0 to the next space
$teaser = substr($text, 0, $space);
} else {
//and if all else fails, just break it poorly
$teaser = substr($text, 0, 50);
}
}