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 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据