PHP将字符串分为两部分
Note: I can't use break or next line functions as i am using FPDF
I am having a problem with php strings. I am having a string where i want to show atmost 12 characters in first row and remaining in second row. So basically i want to break string into two parts and assign to two variables so that i can print those two variables. I have tried following code :-
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();
}
But using this I am getting as shown below :
Original String : The Best Hotel Ever
Output :
The Best Hot
Tel Ever
It is breaking a word, i don't want to break the word, just check the length and if within 12 characters all the words are complete then print next word in next line. Like this :
Desired OutPut:
The Best
Hotel Ever
Any suggestions ?
注意:我不能使用中断或下一行功能,因为我正在使用FPDF p> \ n
我遇到了php字符串的问题。 我有一个字符串,我想在第一行显示最多12个字符,并保持在第二行。 所以基本上我想把字符串分成两部分并分配给两个变量,以便我可以打印这两个变量。 我尝试过以下代码: - p>
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();
}
code> pre>
但是使用这个我得到如下所示: p>
原始字符串:有史以来最好的酒店
输出:
最好的热点
Tel Ever
code>
它打破了一个单词,我不想破坏单词,只需检查长度,如果在12个字符内所有单词都已完成,则在下一行打印下一个单词。 像这样: p>
Desired OutPut:
Best
Hotel Ever
code> pre>
有任何建议吗? p>
div>
I see no built-in function to do it, however you could explode on spaces, and re-build your string until the length with the next words get over 12, everything else going to the second part :
$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" }
Im not too crash hot on PHP but it seems to be a simple case of which element of the string you are accessing is futher across from where you want to be:
Try:
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();
}
For further help check out because you need to remember to count from zero up: http://php.net/manual/en/function.substr.php