2014-09-04 73 views
0

注:由於我使用我有PHP字符串的問題FPDFPHP突破字符串分爲兩個部分

我不能使用break或下一行的功能。我有一個字符串,我想在第一行顯示最多12個字符,並保留在第二行。所以基本上我想把字符串分成兩部分,並分配給兩個變量,以便我可以打印這兩個變量。我曾嘗試下面的代碼: -

if($length > 12) 
     { 
     $first400 = substr($info['business_name'], 0, 12); 
     $theRest = substr($info['business_name'], 11); 
     $this->Cell(140,22,strtoupper($first400)); 
     $this->Ln(); 
     $this->Cell(140,22,strtoupper($theRest)); 
     $this->Ln(); 
     } 

但是使用這個,如下圖所示我越來越:

Original String : The Best Hotel Ever 
Output : 
The Best Hot 
Tel Ever 

它打破了一句話,我不想打破這個詞,只是檢查長度,如果在12個字符以內,所有單詞都完成,則在下一行中打印下一個單詞。像這樣:

Desired OutPut: 
The Best 
Hotel Ever 

有什麼建議嗎?

回答

1

我看沒有內置功能來做到這一點,但你可能會爆炸的空間,並重新建立自己的字符,直到下一個單詞的長度得到超過12,一切要到第二部分:

$string = 'The Best Hotel Ever'; 

$exp = explode(' ', $string); 

if (strlen($exp[0]) < 12) { 
    $tmp = $exp[0]; 
    $i = 1; 
    while (strlen($tmp . ' ' . $exp[$i]) < 12) { 
    $tmp .= " " . $exp[$i]; 
    $i++; 
    } 
    $array[0] = $tmp; 
    while (isset($exp[$i])) { 
    $array[1] .= ' ' . $exp[$i]; 
    $i++; 
    } 
    $array[1] = trim($array[1]); 
} else { 
    $array[0] = ''; 
    $array[1] = trim(implode (' ', $exp)); 
} 

var_dump($array); 

// Output : array(2) { [0]=> string(8) "The Best" [1]=> string(10) "Hotel Ever" } 

// $string1 = 'The'; 
// array(2) { [0]=> string(3) "The" [1]=> string(0) "" } 

// $string2 = 'Thebesthotelever'; 
// array(2) { [0]=> string(0) "" [1]=> string(16) "Thebesthotelever" } 
+0

嗨馬萊,它爲我工作感謝您的幫助。偉大的邏輯:) – 2014-09-04 12:19:37

0

我不是太崩潰PHP的熱,但它似乎是其中的您正在訪問字符串的元素是futher對面,你想成爲一個簡單的例子:

嘗試:

if($length > 12) 
     { 
     $first400 = substr($info['business_name'], 0, 8); 
     $theRest = substr($info['business_name'], 11); 
     $this->Cell(140,22,strtoupper($first400)); 
     $this->Ln(); 
     $this->Cell(140,22,strtoupper($theRest)); 
     $this->Ln(); 
    } 

爲了進一步的幫助檢查,因爲你需要記住從零計數: http://php.net/manual/en/function.substr.php

+0

嗯克萊門特槌有一個更好的答案,但如果有什麼我希望我幫助 – Pariah 2014-09-04 11:48:10

+0

克萊門特槌的解決方案爲我工作,是一個靈活的解決方案。但也感謝你的幫助。 Paiah – 2014-09-04 12:20:58

+0

所有人都很高興能夠做到:D – Pariah 2014-09-04 12:21:44