仅在结束标记后裁剪字符串


Crop the string only after closing tag

如果字符串长度大于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;
?>

我知道我的答案不符合stackoverflow的道德规范,因为我没有时间确切解释它的每个部分是如何工作的。但这是一个我用来裁剪字符串和维护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);