>我有一个最多可以包含 2000 个字符的字符串。我只想显示前 40 个单词。
字符串$row['content']
。我怎么只显示前 50 个?
谢谢。
假设单词用空格分隔。
$words40=explode(" ", $string,41);
unset($words40[40]); // Discard the last element containing the remaining string
当然,这在标点符号上会失败,但由于您没有提到您的字符串是否包含与人类可读语言或任何其他值有关的内容,因此没有理由假设它将是英语语法,因此答案。
参考
最简单的解决方案是 wordwrap()。但是由于你想要 40/50 个单词而不是符号,你应该做这样的事情:
<?php
$string = "Your long string";
$result = preg_split('/((^'p{P}+)|('p{P}*'s+'p{P}*)|('p{P}+$))/', $string, -1, PREG_SPLIT_NO_EMPTY);
$words = implode(' ', array_slice($result, 0 ,50));
?>
正则表达式来自 将文本拆分为单个单词
$wordArray = str_word_count($row['content'], 1);
$wordArraySlice = array_slice($wordArray, 0, 40);
$wordString = implode(" ", $wordArraySlice);
echo $wordString;
此函数计算所有单词并返回一个数组。然后,您可以使用array_slice返回所需的 40 - 50 个单词,然后内爆它们以获得字符串......如果需要帮助,。