2015-12-27 23 views
0

我想顯示一部分字符串;它的60個字符。但它已被剪切,並沒有顯示在單詞上。所以我試過這個:如何使用substr和strpos整個單詞如果我們不知道字符串長度

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

但現在問題是我不知道有多少字符後有空間。 我檢查了50個字符後是否有空格並顯示此子字符串。但是,如果字是多字符,如何檢查它的長度,以便我的最後一個字符串不超過60個字符?

對全字這種顯示子串有沒有更好的解決辦法?

回答

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個字符的最後一個空白。這可以保證您以「整個單詞」終止您的子字符串,同時仍然保持正確的長度不超過60個字符。 strrpos()是一個方便的功能:http://php.net/manual/en/function.strrpos.php

+0

上限我不知道這個功能'strrpos ()' - 這非常有用,謝謝! –

+1

@mistery_girl很值得看看php文檔。特別是功能列表,因爲它們允許您探索您不知道的新功能和特性。例如字符串函數列表:http://php.net/manual/en/ref.strings.php – arkascha

+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; 
+0

我不擅長正則表達式,我必須學習它!謝謝! –

相關問題