Как нарезать строку после точки в PHP?

<?php
function string_excerpt($string, $count){
$words = explode(' ', $string);
if (count($words) > $count)
{
$words = array_slice($words, 0, $count);
$string = implode(' ', $words);
}
return $string;
}

$string = "Some texts";

//The amount of words we want to show
$count = 18;

echo string_excerpt($string, $count);?>

Это код фрагмента текста после подсчета.

Ну, эта функция работает хорошо и вырезать текст после подсчета. Но эта система обрезает строку после любых пометок, например, после «,» или «просто за любое слово». Это должно быть сокращено после «точки».

Вот так: Lorem ipsum doler сидеть амет. Сядь, асд.
после подсчета и отметки: Lorem ipsum doler sit amet.

Что бы ни было в строке, она должна быть обрезана строка после счетчика, и она должна проверять «точку», потому что она должна обрезать после счетчика и «точка».

И что же мне делать?

1

Решение

Попробуйте это решение:

       <?php
function string_excerpt($string, $count){

$words_counter = str_word_count($string);

if ($words_counter > $count)
{
$ans = get_words($string, $count);
$string = str_replace($ans,"",$string);
$sentences  = explode(".",$string);
foreach($sentences as $sentence){
if(str_word_count($ans)>=$count && substr(trim($ans),-1,1)=="."){
return $ans;
}
$ans .= $sentence.".";

}

}
return $string;
}
$string = "Lorem ipsum doler sit amet. Sit done, asd.";

//The amount of words we want to show
$count = 6;
function get_words($string, $count = 18) {
preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $string, $matches);
return $matches[0];
}

echo string_excerpt($string, $count);

?>
1

Другие решения

Так что, если я правильно понимаю.
У вас есть строка После количества слов «length», вы хотите найти следующий после «length» числовой «точка» и вырезать там строку?
Я бы сделал это так:

function string_excerpt($string, $count){
$tmpString = explode(' ',$string);
$returnWord = '';
$id = 0;
foreach($tmpString as $word){
if($id <= $count) {
$returnWord .= $word.' ';
$id++;
}
}
if(strpos($word,'.')===false){// no dot in last word.
for($i=$id; $i<=count($tmpString);$i++){// till we not found dot, add next word
$returnWord .= $tmpString[$i].' ';
if(strpos($tmpString[$i],'.')!==false){//dot found...
break;
}
}
}
return $returnWord;
}
-1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector