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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/965235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:31:00  来源:igfitidea点击:

How can I truncate a string to the first 20 words in PHP?

phpstring

提问by sanders

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

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

回答by karim79

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

回答by nonopolarity

Change the number 3to the number 20below to get the first 20 words, or pass it as parameter. The following demonstrates how to get the first 3 words: (so change the 3to 20to change the default value):

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

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

回答by Hymansonkr

To Nearest Space

到最近空间

Truncates to nearest preceding space of target character. Demo

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

  • $strThe string to be truncated
  • $charsThe amount of characters to be stripped, can be overridden by $to_space
  • $to_spacebooleanfor whether or not to truncate from space near $charslimit
  • $str要截断的字符串
  • $chars要剥离的字符数量,可以被覆盖 $to_space
  • $to_spaceboolean是否从接近$chars极限的空间截断

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

回答by Matthew Vines

use 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

请注意,explode 具有限制功能。所以你可以做类似的事情

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

回答by acecream

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

回答by Assaf Lavie

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 中正则表达式的例子

回答by rajesh

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

回答by Vladyslav Melnychenko

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

回答by lance

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

<space拆分字符串(到数组中)>,然后取该数组的前 20 个元素。

回答by Andrew Hare

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

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.

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

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