dou760663 2014-09-04 11:38 采纳率: 100%
浏览 133
已采纳

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 ?

  • 写回答

2条回答 默认 最新

  • doudinghan8319 2014-09-04 11:46
    关注

    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" }  
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线