2014-09-04 76 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