PHP 条件循环 - 字符串长度


PHP conditional loop - string length

如果这是一个非常愚蠢的问题,或者一个明显的新手错误,我很抱歉 - 但我就像这个基本一样,我几乎从未使用过 do - 而循环之前(我知道 - 我自己无法理解它!这些年来我怎么可能设法避免它??

所以:我想从文本段落的开头选择一些单词。我使用了以下代码:

   $no_of_char = 70;
   $string = $content;
   $string = strip_tags(stripslashes($string)); // convert to plaintext
   $string = substr($string, 0, strpos(wordwrap($string, $no_of_char), "'n"));

哪种有效,但问题是有时它会给出空的结果。我认为这是因为该段落包含空格、空行和/或回车符......所以我正在尝试创建一个循环条件,该条件将继续尝试,直到字符串的长度至少为 X 个字符..

   $no_of_char = 70;  // approximation - how many characters we want
   $string = $content;
do {
       $string = strip_tags(stripslashes($string)); // plaintext
       $string = substr($string, 0, strpos(wordwrap($string, $no_of_char), "'n")); // do not crop words
       } 
while (strlen($string) > 8); // this would be X - and I am guessing here is my problem

好吧 - 显然它不起作用(否则这个问题就不会是) - 现在它总是什么都不产生.(空字符串)

尝试使用 str_word_count:

$words = str_word_count($string, 2);

2 - 返回一个关联数组,其中键是数字 单词在字符串中的位置和值是实际值 单词本身

然后使用array_slice:

$total_words = 70;
$selected_words = array_slice($words, 0, $total_words);

您最可能遇到的问题是字符串开头有空行。您可以使用ltrim()轻松摆脱它们。然后使用原始代码获取第一个实际换行符。

你的循环不起作用的原因是因为你告诉它拒绝任何超过 8 个字符的内容。