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

前端之家收集整理的这篇文章主要介绍了PHP限制文本字符串不包括html标签?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是什么不适合我:
  1. <?PHP
  2. $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.';
  3. $limited = substr($string,100).'...';
  4. echo $string;
  5. ?>

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

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

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

截断HTML代码中单词的函数
  1. //+ Jonas Raoni Soares Silva
  2. //@ http://jsfromhell.com
  3. function truncate($text,$length,$suffix = '&hellip;',$isHTML = true) {
  4. $i = 0;
  5. $simpleTags=array('br'=>true,'hr'=>true,'input'=>true,'image'=>true,'link'=>true,'Meta'=>true);
  6. $tags = array();
  7. if($isHTML){
  8. preg_match_all('/<[^>]+>([^<]*)/',$text,$m,PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
  9. foreach($m as $o){
  10. if($o[0][1] - $i >= $length)
  11. break;
  12. $t = substr(strtok($o[0][0]," \t\n\r\0\x0B>"),1);
  13. // test if the tag is unpaired,then we mustn't save them
  14. if($t[0] != '/' && (!isset($simpleTags[$t])))
  15. $tags[] = $t;
  16. elseif(end($tags) == substr($t,1))
  17. array_pop($tags);
  18. $i += $o[1][1] - $o[0][1];
  19. }
  20. }
  21.  
  22. // output without closing tags
  23. $output = substr($text,$length = min(strlen($text),$length + $i));
  24. // closing tags
  25. $output2 = (count($tags = array_reverse($tags)) ? '</' . implode('></',$tags) . '>' : '');
  26.  
  27. // Find last space or HTML tag (solving problem with last space in HTML tag eg. <span class="new">)
  28. $pos = (int)end(end(preg_split('/<.*>| /',$output,-1,PREG_SPLIT_OFFSET_CAPTURE)));
  29. // Append closing tags to output
  30. $output.=$output2;
  31.  
  32. // Get everything until last space
  33. $one = substr($output,$pos);
  34. // Get the rest
  35. $two = substr($output,$pos,(strlen($output) - $pos));
  36. // Extract all tags from the last bit
  37. preg_match_all('/<(.*?)>/s',$two,$tags);
  38. // Add suffix if needed
  39. if (strlen($text) > $length) { $one .= $suffix; }
  40. // Re-attach tags
  41. $output = $one . implode($tags[0]);
  42.  
  43. //added to remove unnecessary closure
  44. $output = str_replace('</!-->','',$output);
  45.  
  46. return $output;
  47. }

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

猜你在找的PHP相关文章