2014-10-06 164 views
0

如果字符串长度大于80,我想剪切字符串。我需要的是如果字符串包含标记并在开始和结束标记之间剪切字符串,则字符串剪裁应该是只有在关闭标签后。这是我的代码。只有在关闭标记后才剪裁字符串

<?php 
    echo $word='hello good morning<span class="em emj2"></span> <span class="em emj13"></span>  <span class="em emj19"></span> <span class="em emj13"></span> hai'; 
    $a=strlen($word);  
    if($a>80) 
    { 
     echo substr($word,0,80); 
    } 
    else 
     echo $word; 
?> 

回答

1

我知道我的回答并不是很好的道德规范,因为我没有足够的时间来解释它的每一部分是如何工作的。但这是我用来裁剪字符串和维护HTML代码的功能。

function truncate($text, $length, $suffix = '&hellip;', $isHTML = true) { 
    $i = 0; 
    $simpleTags=array('br'=>true,'hr'=>true,'input'=>true,'image'=>true,'link'=>true,'meta'=>true); 
    $tags = array(); 
    if($isHTML){ 
     preg_match_all('/<[^>]+>([^<]*)/', $text, $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); 
     foreach($m as $o){ 
      if($o[0][1] - $i >= $length) 
       break; 
      $t = substr(strtok($o[0][0], " \t\n\r\0\x0B>"), 1); 
      if($t[0] != '/' && (!isset($simpleTags[$t]))) 
       $tags[] = $t; 
      elseif(end($tags) == substr($t, 1)) 
       array_pop($tags); 
      $i += $o[1][1] - $o[0][1]; 
     } 
    } 
    $output = substr($text, 0, $length = min(strlen($text), $length + $i)); 
    $output2 = (count($tags = array_reverse($tags)) ? '</' . implode('></', $tags) . '>' : ''); 
    $pos = (int)end(end(preg_split('/<.*>| /', $output, -1, PREG_SPLIT_OFFSET_CAPTURE))); 
    $output.=$output2; 
    $one = substr($output, 0, $pos); 
    $two = substr($output, $pos, (strlen($output) - $pos)); 
    preg_match_all('/<(.*?)>/s', $two, $tags); 
    if (strlen($text) > $length) { $one .= $suffix; } 
    $output = $one . implode($tags[0]); 
    $output = str_replace('</!-->','',$output); 
    return $output; 
} 

后来干脆像这样:

truncate($your_string, '80', $suffix = '&hellip;', $isHTML = true); 
+0

您的代码将删除tags.I要指定长度内完成的HTML代码的HTML。 – 2014-10-06 08:57:50