2017-09-26 77 views
0

所以我有這個字符串,它太長了,不能放在我的報告中。我的報告應該只使用36個字符。但我的字符串值是不止於此:php子字符串(substr)檢測字符不是字符

$value = "The quick brown fox jumps over the lazy dog" //43 character 

如果只能拿到36字符,所以你會得到:「敏捷的棕色狐狸跳過了第l」 ,但我想除以單詞句子不是由字符,所以我想使2變量

$var1 = "The quick brown fox jumps over the" //instead of The quick brown fox jumps over the l 
$var2 = "lazy dog" 

我該怎麼做?

+0

str_word_count();也許 –

回答

3

您需要在這裏使用wordwrap()。試試這個:

echo substr($value, 0, strpos(wordwrap($value, 36), "\n")); 
0
function limit_text($text, $limit) { 
     if (str_word_count($text, 0) > $limit) { 
      $words = str_word_count($text, 2); 
      $pos = array_keys($words); 
      $text = substr($text, 0, $pos[$limit]) . '...'; 
     } 
     return $text; 
    } 

echo limit_text('The quick brown fox jumps over the lazy dog', 5); 
0

此代碼將在任何給定的字符串工作,通過字addding字和檢查限制每次。

$var1=""; $var2=""; 
$value="your string"; 
while ($var1.strlen<36) { 
    $n=strpos($value, " "); //length of first word 
    if (($var1.strlen +$n)<36) { 
     $var1=$var1+substr($value, 0, $n);//from beginning of value till the first 'space' char 
     $value = substr($value, $n); //removing first word 
    } 
} 
$var2=$value;//the remmaining is what is left for second row 
0

這可能對你有幫助。結果將是陣列包含字符串塊

$value = "The quick brown fox jumps over the lazy dog"; 
$arr = explode(" ",$value); 
$str_arr = array(); 
$str = $arr[0]; 
$char_limit = 36; 
foreach($arr as $key=>$value) 
{ 
    $tmp_str = isset($arr[$key + 1])?$arr[$key + 1]:""; 
    if(strlen($str." ".$tmp_str) <= $char_limit) 
    { 
     $str.=" ".$tmp_str; 
    } 
    else 
    { 
     $str_arr[]=$str; 
     $str=$tmp_str; 
    } 

} 
$str_arr[]=$str; 
print_r ($str_arr); 

DEMO