如果我们不知道字符串长度,如何将 substr 和 strpos 用于整个单词

How to use substr and strpos to whole word if we don't know string length

我正在尝试显示字符串的一部分; 60个字符。但它被剪掉了,没有显示给 while word。所以我尝试了这个:

if(strpos($string, ' ', 50) !== FALSE) { 
     substr($string, 0, strpos($string, ' ', 50))
}elseif(strlen($string) < 50)) {
     echo $string;
}

但是现在,问题是我不知道后面有多少个字符space。 我检查了 50 个字符后是否有 space 并显示了这个子字符串。但是如果word有很多字符,如何检查它的长度,让我最后的子字符串不超过60个字符?

对于这种子串转全字有更好的解决办法吗?

考虑这个例子:

<?php

$subject = <<<EOT
But now, problem is that I don't know after how many characters there is space.
I've checked if there is space after 50 characters and show this substring.
But if word is with many characters, how to check its length, so that my final substring is not more than 60 characters?
EOT;

$lastBlankPos = strrpos(substr($subject, 0, 60), ' ');
var_dump(substr($subject, 0, $lastBlankPos));

输出为:

string(52) "But now, problem is that I don't know after how many"

策略是:查找字符串前60个字符中包含的最后一个空格。这保证您以 "whole word" 终止子字符串,同时长度仍保持在 60 个字符以下。 strrpos() 是一个方便的函数:http://php.net/manual/en/function.strrpos.php

这应该 return 完整的单词,如果它恰好在 60 的上限

    $maxlength=60;

    $str_text="But now, problem is that I don't know after how many characters there is space. 
    I've checked if there is space after 50 characters and show this substring. But if word is 
    with many characters, how to check its length, so that my final substring is not more than 
    60 characters?";

    $trimmed=rtrim( preg_replace('/\s+?(\S+)?$/', '', substr( $str_text, 0, $maxlength+1 ) ), ',' );

    echo $trimmed;