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

时间:2015-12-27 12:29:19

标签: php string substr

我试图显示字符串的一部分; 60个字符。但是它被剪切而不是显示在文字中。所以我尝试了这个:

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

但现在,问题是我不知道有多少个角色有空间。 我检查了50个字符后是否有空格并显示此子字符串。但是如果单词有很多字符,如何检查它的长度,以便我的最终子字符串不超过60个字符?

对于整个单词这种显示子字符串是否有更好的解决方案?

2 个答案:

答案 0 :(得分:2)

这应该返回整个单词而不会破坏一个单词,如果恰好是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;

答案 1 :(得分:1)

考虑这个例子:

<?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个字符中包含的最后一个空格。这可以保证您使用&#34;整个单词&#34;来终止子字符串。同时仍然保持在60个字符以下。 strrpos()是一个方便的功能:http://php.net/manual/en/function.strrpos.php