2011-07-14 25 views
3

正如標題所說我想剪一個字符串,不違反任何文字或HTML標籤的任何文字或HTML標籤,現在我發現這個功能,這種種的HTML標籤問題出(由我自己稍微修改)PHP如何切串不破壞

function substrhtml($str,$start,$len){ 

    $str_clean = substr(strip_tags($str),$start,$len); 

    if(preg_match_all('/\<[^>]+>/is',$str,$matches,PREG_OFFSET_CAPTURE)){ 

     for($i=0;$i<count($matches[0]);$i++){ 

      if($matches[0][$i][1] < $len){ 

       $str_clean = substr($str_clean,0,$matches[0][$i][1]) . $matches[0][$i][0] . substr($str_clean,$matches[0][$i][1]); 

      }else if(preg_match('/\<[^>]+>$/is',$matches[0][$i][0])){ 

       $str_clean = substr($str_clean,0,$matches[0][$i][1]) . $matches[0][$i][0] . substr($str_clean,$matches[0][$i][1]); 

       break; 

      } 

     } 

     return $str_clean; 

    }else{ 

     return substr($str,$start,$len); 

    } 

} 

Source

,但它仍然減少了一半中旬句話,我不希望發生的事情,對任何想法如何排序呢?

與往常一樣,任何幫助表示感謝,並提前致謝。

+0

相關:http://stackoverflow.com/questions/4738160/workaround-for-the-990-character-limitation-for-email-mailservers –

+0

試試這個鏈接可能會幫助你... http://stackoverflow.com/a/26098951/3944217 – edCoder

回答

3

試試這個:

function substrhtml($str,$start,$len){ 

    $str_clean = substr(strip_tags($str),$start,$len); 
    $pos = strrpos($str_clean, " "); 
    if($pos === false) { 
     $str_clean = substr(strip_tags($str),$start,$len); 
     }else 
     $str_clean = substr(strip_tags($str),$start,$pos); 

    if(preg_match_all('/\<[^>]+>/is',$str,$matches,PREG_OFFSET_CAPTURE)){ 

     for($i=0;$i<count($matches[0]);$i++){ 

      if($matches[0][$i][1] < $len){ 

       $str_clean = substr($str_clean,0,$matches[0][$i][1]) . $matches[0][$i][0] . substr($str_clean,$matches[0][$i][1]); 

      }else if(preg_match('/\<[^>]+>$/is',$matches[0][$i][0])){ 

       $str_clean = substr($str_clean,0,$matches[0][$i][1]) . $matches[0][$i][0] . substr($str_clean,$matches[0][$i][1]); 

       break; 

      } 

     } 

     return $str_clean; 

    }else{ 
     $string = substr($str,$start,$len); 
     $pos = strrpos($string, " "); 
     if($pos === false) { 
      return substr($str,$start,$len); 
     } 
      return substr($str,$start,$pos); 

    } 

} 
$string = '<h1>How to cut the string without breaking any words</h1>'; 
echo substrhtml($string,0,28); 
?> 
+1

這並不像預期的那樣工作... – Bernat

+0

它爲我工作:) – Naeem

0
<?php 

$string = 'When one thinks of luxury travel throughout the Mediterranean, a handful of destinations are bound to be at the top of the list, destinations like the French Riviera, the Grecian Islands, or the Italian coastline.'; 

echo current(explode('::BR::', wordwrap($string, 20, '::BR::'))); 
?>