2012-09-21 41 views
0

我需要将文本拆分为两个部分,该函数可以完成但它在一个单词中间切断,我需要它来计算单词给出的开始或结束或采取几个字符。在125个字符后将文本字段拆分为两部分

因为我需要的字符范围不超过130个字符,所以我无法将它基于字数。

$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem  Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown  printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum" 

$first125 = substr($str, 0, 125); 
$theRest = substr($str, 125); 

感谢

回答

1

这里是一个非常基本的解决方案,你想要做的就是你开始

$first125 = substr($str, 0, 125); 
$theRest = substr($str, 125); 

$remainder_pieces = explode(" ", $theRest, 2); 

$first125 .= $remainder_pieces[0]; 
$theRest = $remainder_pieces[1]; 

echo $first125."</br>"; 
echo $theRest; 

,但还有更多的事情需要考虑,例如使用该解决方案,如果125字符一个单词结束后的空格,它会包含另一个单词,因此您可能需要添加一些其他检查方法以尽可能准确地进行尝试。

+0

完美,非常感谢! – ConquestXD

0

不知道那里有一个本地的PHP函数把我的头顶部,但我认为这应该为你工作。当然,你需要添加一些东西来检查是否至少有125个字符,并且在第125个字符之后是否有空格。

$k = 'a'; 
    $i = 0; 
    while($k != ' '): 
     $k = substr($str, (125+$i), 1); 
     if($k == ' '): 
     $first125 = substr($str, 0, (125+$i)); 
     $theRest = substr($str, (125+$i+1)); 
     else: 
      $i++; 
     endif; 
    endwhile; 
2

尝试:

<?php 
$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem  Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown  printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum"; 
$str = explode(' ', $str); 
$substr = ""; 

foreach ($str as $cur) { 
    if (strlen($substr) >= 125) { 
     break; 
    } 
    $substr .= $cur . ' '; 
} 
echo $substr; 
?> 

键盘http://codepad.org/EhgbdDeJ