如何在PHP中点后切换字符串?

时间:2017-02-19 19:42:33

标签: 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);?>

这是计数后切片文本的代码。

好吧,这个功能运行良好并且在计数后剪切文本。但是这个系统在任何标记之后切断了字符串,例如&#34;,&#34;或者&#34;任何单词&#34;。它必须在&#34; dot&#34;之后切断。

像那样:Lorem ipsum doler坐着。坐完了,asd。 计数和复选标记后:Lorem ipsum doler坐下来。

无论字符串是什么,都必须在计数后剪切字符串,并且必须检查“点”字符串。因为它必须在数量之后削减并且点数为

那我该怎么办?

2 个答案:

答案 0 :(得分: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 :(得分:-1)

所以,如果我理解正确的话。 你有一些字符串。在&#34;长度&#34;你希望在&#34;长度&#34;之后找到的单词数量。 numer&#34; dot&#34;并切断那里的字符串? 我会这样做:

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;
}