2012-09-21 42 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