PHP限制文本字符串不包括html标签?

这是什么不适合我:
<?PHP
 $string = 'I have a dog and his name is <a href="http://www.jackismydog.com">Jack</a> and I love him very much because he\'s my favorite dog in the whole wide world and nothing Could make me not love him,I think.';
 $limited = substr($string,100).'...';
 echo $string;
?>

我想将VISIBLE文本限制为100个字符,但使用substr()包括限制中的不可见文本(< a href =“http://www.jackismydog.com”>和< / a>)占用了100个可用字符中的41个.

有没有办法限制文本,以便链接中的单词“杰克”将包含在限制中,但不包括< a href =“http://www.jackismydog.com”>或< / a>?

编辑:
我想保留字符串中的链接,只是不计算它的限制长度..

截断HTML代码中单词的函数
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com
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);
            // test if the tag is unpaired,then we mustn't save them
            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 without closing tags
    $output = substr($text,$length = min(strlen($text),$length + $i));
    // closing tags
    $output2 = (count($tags = array_reverse($tags)) ? '</' . implode('></',$tags) . '>' : '');

    // Find last space or HTML tag (solving problem with last space in HTML tag eg. <span class="new">)
    $pos = (int)end(end(preg_split('/<.*>| /',$output,-1,PREG_SPLIT_OFFSET_CAPTURE)));
    // Append closing tags to output
    $output.=$output2;

    // Get everything until last space
    $one = substr($output,$pos);
    // Get the rest
    $two = substr($output,$pos,(strlen($output) - $pos));
    // Extract all tags from the last bit
    preg_match_all('/<(.*?)>/s',$two,$tags);
    // Add suffix if needed
    if (strlen($text) > $length) { $one .= $suffix; }
    // Re-attach tags
    $output = $one . implode($tags[0]);

    //added to remove  unnecessary closure
    $output = str_replace('</!-->','',$output); 

    return $output;
}

资料来源:http://snippets.dzone.com/posts/show/7125

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...