2013-02-05 164 views
1

我想通过(例如)50个符号(分钟)来炸开一个字符串,但没有将单词分成两部分。按字符数拆分字符串而不拆分单词

这可能吗?

使用str_split()会导致最后一个词被拆分,这是我不要想要的。

示例:将字符串拆分为5个符号;

$input = 'This is example, example can be anything.'; 

$output[0] = 'This'; 
$output[1] = 'is example,'; 
$output[2] = 'example'; 
$output[3] = 'can'; 
$output[4] = 'be anything'; 
+3

可你给输入/输出的例子吗? – x4rf41

+0

@ x4rf41我添加了一个例子来发布 –

+1

为什么“这是”没有拆分,但“可以”拆分?分裂背后的逻辑是什么? – x4rf41

回答

3

我不认为有一个内置单功能,将做到这一点给你,但你可以做这样的事情:

Codepad Example Here

$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque nec elit dui, nec fermentum velit. Nullam congue ipsum ac quam auctor nec massa nunc."; 

$output = array(); 
while (strlen($string) > 50) { 
    $index = strpos($string, ' ', 50); 
    $output[] = trim(substr($string, 0, $index)); 
    $string = substr($string, $index); 
} 
$output[] = trim($string); 

var_dump($output); 

// array(3) { 
// [0]=> 
// string(50) "Lorem ipsum dolor sit amet, consectetur adipiscing" 
// [1]=> 
// string(55) "elit. Quisque nec elit dui, nec fermentum velit. Nullam" 
// [2]=> 
// string(43) "congue ipsum ac quam auctor nec massa nunc." 
// } 
+0

这是我需要感谢 –

0

只要通过字符串,并在一个数字(数字= 5)的字符后检查是否下一个字符是空格和分裂。如果没有空间,不要分裂并转到下一个空格:-)

0

我想我明白你为好,那么你可以使用此功能:

<?php 

    function str_split_len($str, $len) 
    { 
     if($len > strlen($str)) 
     { 
      return false; 
     } 

     $strlen = strlen($str); 
     $result = array(); 
     $words = ($strlen/$len); 

     for($x = 1; $x <= $len; $x++) 
     { 
      $result[] = substr($str, 0, $words); 
      $str = substr($str, $words, $strlen); 
     } 

     return $result; 
    } 

    /* Example */ 
    $res = str_split_len("Split me !haha!", 3); 
    print_r($res); 
?> 
+1

没有你的功能分词,尝试更长的字符串 –