如何在 PHP 中将字符串截断为前20个单词?

如何在 PHP 中截断20个单词后的字符串?

149606 次浏览

通过 <space>将字符串拆分(成一个数组) ,然后获取该数组的前20个元素。

试试正则表达式。

你需要一些能够匹配20个单词(或者20个单词边界)的东西。

因此(我的正则表达式很糟糕,所以如果这不准确,请纠正我) :

/(\w+\b){20}/

这是 Php 中正则表达式的一些例子

function limit_text($text, $limit) {
if (str_word_count($text, 0) > $limit) {
$words = str_word_count($text, 2);
$pos   = array_keys($words);
$text  = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}


echo limit_text('Hello here is a long sentence that will be truncated by the', 5);

产出:

Hello here is a long ...

像这样的东西可能会奏效:

<?php
$words = implode(' ', array_slice(split($input, ' ', 21), 0, 20));

使用 爆炸

来自文件的例子。

// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

请注意,爆炸有一个极限函数。所以你可以这样做

$message = implode(" ", explode(" ", $long_message, 20));

循环使用 PHP 标记器函数 ()

$token = strtok($string, " "); // we assume that words are separated by sapce or tab
$i = 0;
$first20Words = '';
while ($token !== false && $i < 20) {
$first20Words .= $token;
$token = strtok(" ");
$i++;
}
echo $first20Words;

将数字 3更改为下面的数字 20以获得前20个单词,或将其作为参数传递。下面演示如何获取前三个单词: (将 3更改为 20以更改默认值):

function first3words($s, $limit=3) {
return preg_replace('/((\w+\W*){'.($limit-1).'}(\w+))(.*)/', '${1}', $s);
}


var_dump(first3words("hello yes, world wah ha ha"));  # => "hello yes, world"
var_dump(first3words("hello yes,world wah ha ha"));   # => "hello yes,world"
var_dump(first3words("hello yes world wah ha ha"));   # => "hello yes world"
var_dump(first3words("hello yes world"));  # => "hello yes world"
var_dump(first3words("hello yes world.")); # => "hello yes world"
var_dump(first3words("hello yes"));  # => "hello yes"
var_dump(first3words("hello"));  # => "hello"
var_dump(first3words("a")); # => "a"
var_dump(first3words(""));  # => ""

怎么了

chunk_split($str,20);

进入 PHP 手册

基于動不動能量的答案:

function truncate_words($string,$words=20) {
return preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string);
}

或者

function truncate_words_with_ellipsis($string,$words=20,$ellipsis=' ...') {
$new = preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string);
if($new != $string){
return $new.$ellipsis;
}else{
return $string;
}


}

以下是我实现的内容。

function summaryMode($text, $limit, $link) {
if (str_word_count($text, 0) > $limit) {
$numwords = str_word_count($text, 2);
$pos = array_keys($numwords);
$text = substr($text, 0, $pos[$limit]).'... <a href="'.$link.'">Read More</a>';
}
return $text;
}

正如您所看到的,它是基于 karim79的答案,所有需要修改的是 if 语句还需要检查单词而不是字符。

为了方便起见,我还添加了一个到 main 函数的链接。到目前为止,它的工作完美无瑕。多亏了最初的解决方案提供商。

这是我用的一个:

    $truncate = function( $str, $length ) {
if( strlen( $str ) > $length && false !== strpos( $str, ' ' ) ) {
$str = preg_split( '/ [^ ]*$/', substr( $str, 0, $length ));
return htmlspecialchars($str[0]) . '&hellip;';
} else {
return htmlspecialchars($str);
}
};
return $truncate( $myStr, 50 );

它不是我自己的创造,它是以前的帖子的修改。

function limit_text($text, $limit) {
$strings = $text;
if (strlen($text) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
if(sizeof($pos) >$limit)
{
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
return $text;
}

到最近的空间

截断到目标字符的最接近前面的空格

  • 要截断的字符串
  • 要剥离的字符数量,可以被 $to_space覆盖
  • $to_space boolean是否从接近 $chars极限的空间截断

功能

function truncateString($str, $chars, $to_space, $replacement="...") {
if($chars > strlen($str)) return $str;


$str = substr($str, 0, $chars);
$space_pos = strrpos($str, " ");
if($to_space && $space_pos >= 0)
$str = substr($str, 0, strrpos($str, " "));


return($str . $replacement);
}

样本

<?php


$str = "this is a string that is just some text for you to test with";


print(truncateString($str, 20, false) . "\n");
print(truncateString($str, 22, false) . "\n");
print(truncateString($str, 24, true) . "\n");
print(truncateString($str, 26, true, " :)") . "\n");
print(truncateString($str, 28, true, "--") . "\n");


?>

输出

this is a string tha...
this is a string that ...
this is a string that...
this is a string that is :)
this is a string that is--

另一个解决方案:)

$aContent = explode(' ', $cContent);
$cContent = '';
$nCount = count($aContent);
for($nI = 0; ($nI < 20 && $nI < $nCount); $nI++) {
$cContent .= $aContent[$nI] . ' ';
}
trim($cContent, ' ');
echo '<p>' . $cContent . '</p>';

简单且完全配备的 truncate ()方法:

function truncate($string, $width, $etc = ' ..')
{
$wrapped = explode('$trun$', wordwrap($string, $width, '$trun$', false), 2);
return $wrapped[0] . (isset($wrapped[1]) ? $etc : '');
}

有三个点:

function limitWords($text, $limit) {
$word_arr = explode(" ", $text);


if (count($word_arr) > $limit) {
$words = implode(" ", array_slice($word_arr , 0, $limit) ) . ' ...';
return $words;
}


return $text;
}

这对 联码(UTF8)的句子也很管用:

function myUTF8truncate($string, $width){
if (mb_str_word_count($string) > $width) {
$string= preg_replace('/((\w+\W*|| [\p{L}]+\W*){'.($width-1).'}(\w+))(.*)/', '${1}', $string);
}
return $string;
}

试试以下代码,

 $text  = implode(' ', array_slice(explode(' ', $text), 0, 32))
echo $text;

为了限制用词,我使用了以下小代码:

    $string = "hello world ! I love chocolate.";
$explode = array_slice(explode(' ', $string), 0, 4);
$implode = implode(" ",$explode);
echo $implode;

$implot will give: hello world! I

function getShortString($string,$wordCount,$etc = true)
{
$expString = explode(' ',$string);
$wordsInString = count($expString);
if($wordsInString >= $wordCount )
{
$shortText = '';
for($i=0; $i < $wordCount-1; $i++)
{
$shortText .= $expString[$i].' ';
}
return  $etc ? $shortText.='...' : $shortText;
}
else return $string;
}

假设我们有字符串变量 $字符串$开始$极限,我们可以从 PHP 中借用3或4个函数来实现这一点。他们是:

  • Script _ tag () PHP 函数删除不必要的 HTML 和 PHP 标签(如果有的话)。如果没有 HTML 或 PHP 标签,这是不必要的。
  • () $字符串分割成一个数组
  • Array _ splice () 来指定单词的数量以及从哪里开始 它将被分配给我们的 $开始$极限变量的值所控制。
  • 最后,内爆将数组元素连接到截断的 绳子。

    function truncateString($string, $start, $limit){
    $stripped_string =strip_tags($string); // if there are HTML or PHP tags
    $string_array =explode(' ',$stripped_string);
    $truncated_array = array_splice($string_array,$start,$limit);
    $truncated_string=implode(' ',$truncated_array);
    
    
    return $truncated_string;
    }
    

It's that simple..

I hope this was helpful.

function limitText($string,$limit){
if(strlen($string) > $limit){
$string = substr($string, 0,$limit) . "...";
}
return $string;
}

这将返回20个单词。我希望它将有所帮助

我完成了我的使命:

function summery($text, $limit) {
$words=preg_split('/\s+/', $text);
$count=count(preg_split('/\s+/', $text));
if ($count > $limit) {
$text=NULL;
for($i=0;$i<$limit;$i++)
$text.=$words[$i].' ';
$text.='...';
}
return $text;
}

如果你在 Laravel 上编写代码,只需要 use Illuminate\Support\Str

这里有个例子

Str::words($category->publication->title, env('WORDS_COUNT_HOME'), '...')

希望这对你有帮助。

$text='some text';
$len=strlen($text);
$limit=500;
// char
if($len>$limit){
$text=substr($text,0,$limit);
$words=explode(" ", $text);
$wcount=count($words);
$ll=strlen($words[$wcount]);
$text=substr($text,0,($limit-$ll+1)).'...';
}
    function limit_word($start,$limit,$text){
$limit=$limit-1;
$stripped_string =strip_tags($text);
$string_array =explode(' ',$stripped_string);
if(count($string_array)>$limit){
$truncated_array = array_splice($string_array,$start,$limit);
$text=implode(' ',$truncated_array).'...';
return($text);
}
else{return($text);}
}
function wordLimit($str, $limit) {
$arr = explode(' ', $str);
if(count($arr) <= $limit){
return $str;
}
$result = '';
for($i = 0; $i < $limit; $i++){
$result .= $arr[$i].' ';
}
return trim($result);
}
echo wordLimit('Hello Word', 1); // Hello
echo wordLimit('Hello Word', 2); // Hello Word
echo wordLimit('Hello Word', 3); // Hello Word
echo wordLimit('Hello Word', 0); // ''

我会用 explode()array_pop()implode(),例如:

$long_message = "I like summer, also I like winter and cats, btw dogs too!";


$trimmed_message = explode(" ", $long_message, 5); // <-- '5' means 4 words to be returned
array_pop($trimmed_message); //removing last element from exploded array
$trimmed_message = implode(" ", $trimmed_message) . '...';

结果:

I like summer, also...

比之前发布的所有正则表达式技术都要简单,只需匹配非单词的前 n 个序列,然后匹配单词字符序列。使非单词字符成为可选的允许从字符串的开始匹配单词字符。贪婪的单词字符匹配确保了连续的单词字符永远不会被视为单个单词。

通过在匹配 n 个子字符串之后在模式中写入 \K,然后匹配字符串的其余部分(如果需要点来匹配换行,则添加 s模式修饰符) ,替换可以是一个空字符串。

密码: (演示)

function firstNWords(string $string, int $limit = 3) {
return preg_replace("/(?:\W*\w+)\{\{$limit}}\K.*/", '', $string);
}