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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?