Как насчет этого?
/**
* @param string $text
* @param int $limit
* @return string
*/
public function extractUncutPhrase($text, $limit)
{
$delimiters = [',',' '];
$marks = ['!','?','.'];
$phrase = substr($text, 0, $limit);
$nextSymbol = substr($text, $limit, 1);
// Equal to original
if ($phrase == $text) {
return $phrase;
}
// If ends with delimiter
if (in_array($nextSymbol, $delimiters)) {
return $phrase;
}
// If ends with mark
if (in_array($nextSymbol, $marks)) {
return $phrase.$nextSymbol;
}
$parts = explode(' ', $phrase);
array_pop($parts);
return implode(' ', $parts); // Additioanally you may add ' ...' here.
}
Тесты:
public function testExtractUncutPhrase()
{
$stringUtils = new StringUtils();
$text = 'infant ton-gue could make of both names nothing';
$phrase = 'infant';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 11));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 12));
$text = 'infant tongue5';
$phrase = 'infant';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 11));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 7));
}
public function testExtractUncutPhraseEndsWithDelimiter()
{
$stringUtils = new StringUtils();
$text = 'infant tongue ';
$phrase = 'infant tongue';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
$text = 'infant tongue,';
$phrase = 'infant tongue';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
}
public function testExtractUncutPhraseIsSentence()
{
$stringUtils = new StringUtils();
$text = 'infant tongue!';
$phrase = 'infant tongue!';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 14));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 100));
$text = 'infant tongue!';
$phrase = 'infant tongue!';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
$text = 'infant tongue.';
$phrase = 'infant tongue.';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
}
Попробуйте эту ссылку, может помочь вам ... http://stackoverflow.com/a/26098951/3944217 – edCoder
В несвязанной материи, зачем использовать '' $ body'', а не просто '$ body'? – TRiG