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

时间:2021-01-20 21:36:11

How can I truncate a string after 20 words in PHP?

如何在PHP中删除20个单词后的字符串?

24 个解决方案

#1


113  

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 blah blah blah blah blah hahahaha haha haaaaaa', 5);

Outputs:

输出:

Hello here is a long ...

#2


24  

change the number 2 to the number 19 below to get the first 20 words. The following demonstrates using 2 to get the first 3 words: (so change the 2 to 19 and it will give you the first 20 words)

将数字2更改为下面的数字19以获得前20个单词。以下演示使用2获取前3个单词:(因此将2更改为19,它将为您提供前20个单词)

function first3words($s) {
    return preg_replace('/((\w+\W*){2}(\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(""));  # => ""

#3


9  

To Nearest Space

Truncates to nearest preceding space of target character. Demo

截断到目标字符的最近前空格。演示

  • $str The string to be truncated
  • $ str要截断的字符串
  • $chars The amount of characters to be stripped, can be overridden by $to_space
  • $ chars要删除的字符数,可以被$ to_space覆盖
  • $to_space boolean for whether or not to truncate from space near $chars limit
  • $ to_space布尔值,表示是否从$ chars limit附近的空格截断

Function

功能

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

Sample

样品

<?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");

?>

Output

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

#4


6  

use explode() .

使用explode()。

Example from the docs.

来自文档的示例。

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

note that explode has a limit function. So you could do something like

请注意,爆炸具有限制功能。所以你可以做点什么

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

#5


6  

Simple and fully equiped truncate() method:

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

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

#6


5  

Try regex.

试试正则表达式。

You need something that would match 20 words (or 20 word boundaries).

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

So (my regex is terrible so correct me if this isn't accurate):

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

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

And here are some examples of regex in php.

以下是php中正则表达式的一些示例。

#7


5  

Its not my own creation, its a modification of previous posts. credits goes to karim79.

它不是我自己的创作,它是以前帖子的修改。积分去karim79。

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

#8


4  

Split the string (into an array) by <space>, and then take the first 20 elements of that array.

通过 拆分字符串(到数组中),然后获取该数组的前20个元素。

#9


4  

This looks pretty good to me:

这看起来对我很好:

A common problem when creating dynamic web pages (where content is sourced from a database, content management system or external source such as an RSS feed) is that the input text can be too long and cause the page layout to 'break'.

创建动态网页(其中内容源自数据库,内容管理系统或外部源(如RSS源))的常见问题是输入文本可能太长并导致页面布局“中断”。

One solution is to truncate the text so that it fits on the page. This sounds simple, but often the results aren't as expected due to words and sentences being cut off at inappropriate points.

一种解决方案是截断文本以使其适合页面。这听起来很简单,但由于在不适当的地方切断了单词和句子,结果往往不如预期。

#10


3  

With triple dots:

有三个点:

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

#11


2  

Something like this could probably do the trick:

像这样的东西可能会做到这一点:

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

#12


2  

use PHP tokenizer function strtok() in a loop.

在循环中使用PHP tokenizer函数strtok()。

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

#13


2  

based on 動靜能量's answer:

根据动静能量的回答:

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

or

要么

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

}

#14


1  

Here is what I have implemented.

这是我实施的内容。

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

As you can see it is based off karim79's answer, all that needed changing was that the if statement also needed to check against words not characters.

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

I also added a link to main function for convenience. So far it hsa worked flawlessly. Thanks to the original solution provider.

为方便起见,我还添加了一个主要功能的链接。到目前为止,它完美无瑕地工作。感谢原始解决方案提供商。

#15


1  

Here's one I use:

这是我使用的一个:

    $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 );

#16


1  

Another solution :)

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

#17


1  

This worked me for UNICODE (UTF8) sentences too:

这对我来说也是UNICODE(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;
}

#18


1  

Try below code,

试试下面的代码,

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

#19


1  

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

#20


0  

To limit words, am using the following little code :

要限制单词,我使用以下小代码:

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

$implot will give : hello world ! I

$ implot会给:你好世界!一世

#21


0  

Lets assume we have the string variables $string, $start, and $limit we can borrow 3 or 4 functions from PHP to achieve this. They are:

让我们假设我们有字符串变量$ string,$ start和$ limit我们可以从PHP借用3或4个函数来实现这一点。他们是:

  • script_tags() PHP function to remove the unnecessary HTML and PHP tags (if there are any). This wont be necessary, if there are no HTML or PHP tags.
  • script_tags()PHP函数删除不必要的HTML和PHP标记(如果有的话)。如果没有HTML或PHP标记,则不需要这样做。
  • explode() to split the $string into an array
  • explode()将$ string拆分为数组
  • array_splice() to specify the number of words and where it'll start from. It'll be controlled by vallues assigned to our $start and $limit variables.
  • array_splice()指定单词的数量以及它从哪里开始。它将由分配给$ start和$ limit变量的vallues控制。
  • and finally, implode() to join the array elements into your truncated string..

    最后,implode()将数组元素连接到截断的字符串中..

    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.

我希望这可以帮到你。

#22


0  

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

this will return 20 words and then I hope it will help

这将返回20个字然后我希望它会有所帮助

#23


0  

I made my function:

我完成了我的职责:

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

#24


-1  

what about

关于什么

chunk_split($str,20);

Entry in the PHP Manual

在PHP手册中输入

#1


113  

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 blah blah blah blah blah hahahaha haha haaaaaa', 5);

Outputs:

输出:

Hello here is a long ...

#2


24  

change the number 2 to the number 19 below to get the first 20 words. The following demonstrates using 2 to get the first 3 words: (so change the 2 to 19 and it will give you the first 20 words)

将数字2更改为下面的数字19以获得前20个单词。以下演示使用2获取前3个单词:(因此将2更改为19,它将为您提供前20个单词)

function first3words($s) {
    return preg_replace('/((\w+\W*){2}(\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(""));  # => ""

#3


9  

To Nearest Space

Truncates to nearest preceding space of target character. Demo

截断到目标字符的最近前空格。演示

  • $str The string to be truncated
  • $ str要截断的字符串
  • $chars The amount of characters to be stripped, can be overridden by $to_space
  • $ chars要删除的字符数,可以被$ to_space覆盖
  • $to_space boolean for whether or not to truncate from space near $chars limit
  • $ to_space布尔值,表示是否从$ chars limit附近的空格截断

Function

功能

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

Sample

样品

<?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");

?>

Output

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

#4


6  

use explode() .

使用explode()。

Example from the docs.

来自文档的示例。

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

note that explode has a limit function. So you could do something like

请注意,爆炸具有限制功能。所以你可以做点什么

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

#5


6  

Simple and fully equiped truncate() method:

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

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

#6


5  

Try regex.

试试正则表达式。

You need something that would match 20 words (or 20 word boundaries).

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

So (my regex is terrible so correct me if this isn't accurate):

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

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

And here are some examples of regex in php.

以下是php中正则表达式的一些示例。

#7


5  

Its not my own creation, its a modification of previous posts. credits goes to karim79.

它不是我自己的创作,它是以前帖子的修改。积分去karim79。

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

#8


4  

Split the string (into an array) by <space>, and then take the first 20 elements of that array.

通过 拆分字符串(到数组中),然后获取该数组的前20个元素。

#9


4  

This looks pretty good to me:

这看起来对我很好:

A common problem when creating dynamic web pages (where content is sourced from a database, content management system or external source such as an RSS feed) is that the input text can be too long and cause the page layout to 'break'.

创建动态网页(其中内容源自数据库,内容管理系统或外部源(如RSS源))的常见问题是输入文本可能太长并导致页面布局“中断”。

One solution is to truncate the text so that it fits on the page. This sounds simple, but often the results aren't as expected due to words and sentences being cut off at inappropriate points.

一种解决方案是截断文本以使其适合页面。这听起来很简单,但由于在不适当的地方切断了单词和句子,结果往往不如预期。

#10


3  

With triple dots:

有三个点:

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

#11


2  

Something like this could probably do the trick:

像这样的东西可能会做到这一点:

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

#12


2  

use PHP tokenizer function strtok() in a loop.

在循环中使用PHP tokenizer函数strtok()。

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

#13


2  

based on 動靜能量's answer:

根据动静能量的回答:

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

or

要么

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

}

#14


1  

Here is what I have implemented.

这是我实施的内容。

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

As you can see it is based off karim79's answer, all that needed changing was that the if statement also needed to check against words not characters.

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

I also added a link to main function for convenience. So far it hsa worked flawlessly. Thanks to the original solution provider.

为方便起见,我还添加了一个主要功能的链接。到目前为止,它完美无瑕地工作。感谢原始解决方案提供商。

#15


1  

Here's one I use:

这是我使用的一个:

    $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 );

#16


1  

Another solution :)

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

#17


1  

This worked me for UNICODE (UTF8) sentences too:

这对我来说也是UNICODE(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;
}

#18


1  

Try below code,

试试下面的代码,

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

#19


1  

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

#20


0  

To limit words, am using the following little code :

要限制单词,我使用以下小代码:

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

$implot will give : hello world ! I

$ implot会给:你好世界!一世

#21


0  

Lets assume we have the string variables $string, $start, and $limit we can borrow 3 or 4 functions from PHP to achieve this. They are:

让我们假设我们有字符串变量$ string,$ start和$ limit我们可以从PHP借用3或4个函数来实现这一点。他们是:

  • script_tags() PHP function to remove the unnecessary HTML and PHP tags (if there are any). This wont be necessary, if there are no HTML or PHP tags.
  • script_tags()PHP函数删除不必要的HTML和PHP标记(如果有的话)。如果没有HTML或PHP标记,则不需要这样做。
  • explode() to split the $string into an array
  • explode()将$ string拆分为数组
  • array_splice() to specify the number of words and where it'll start from. It'll be controlled by vallues assigned to our $start and $limit variables.
  • array_splice()指定单词的数量以及它从哪里开始。它将由分配给$ start和$ limit变量的vallues控制。
  • and finally, implode() to join the array elements into your truncated string..

    最后,implode()将数组元素连接到截断的字符串中..

    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.

我希望这可以帮到你。

#22


0  

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

this will return 20 words and then I hope it will help

这将返回20个字然后我希望它会有所帮助

#23


0  

I made my function:

我完成了我的职责:

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

#24


-1  

what about

关于什么

chunk_split($str,20);

Entry in the PHP Manual

在PHP手册中输入