How to truncate a string in PHP to the sentence closest to a certain number of characters?

后端 未结 4 1709
余生分开走
余生分开走 2020-12-20 20:38

I want to truncate/shorten my string to the sentence closest to a ceratain number of characters.

I have a working function, but my function truncate to the word clos

4条回答
  •  不思量自难忘°
    2020-12-20 20:50

    You could just use a simple regular expression like /^([^.]*?).*/ and replace that with "$1". Like:

    $output = preg_replace('/^([^.]+).*/', '$1.', $input);
    

    That said, you'll have to be aware that not all languages have period (.) as the sentence delimiter.

    HTH.

提交回复
热议问题