php 不破坏单词截取字符串的简单示例

前端之家收集整理的这篇文章主要介绍了php 不破坏单词截取字符串的简单示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。
经测试代码如下: @H_404_3@<?PHP /** * 截取字符串 * * @param * @arrange (512.笔记) jb51.cc * snippet(phrase,[max length],[phrase tail]) * snippetgreedy(phrase,[max length before next space],[phrase tail]) **/ function snippet($text,$length=64,$tail="...") { $text = trim($text); $txtl = strlen($text); if($txtl > $length) { for($i=1;$text[$length-$i]!=" ";$i++) { if($i == $length) { return substr($text,$length) . $tail; } } $text = substr($text,$length-$i+1) . $tail; } return $text; } // It behaves greedy,gets length characters ore goes for more function snippetgreedy($text,$tail="...") { $text = trim($text); if(strlen($text) > $length) { for($i=0;$text[$length+$i]!=" ";$i++) { if(!$text[$length+$i]) { return $text; } } $text = substr($text,$length+$i) . $tail; } return $text; } // The same as the snippet but removing latest low punctuation chars,// if they exist (dots and commas). It performs a later suffixal trim of spaces function snippetwop($text,$length) . $tail; } } for(;$text[$length-$i]=="," || $text[$length-$i]=="." || $text[$length-$i]==" ";$i++) {;} $text = substr($text,$length-$i+1) . $tail; } return $text; } /* echo(snippet("this is not too long to run on the column on the left,perhaps,or perhaps yes,no idea") . "<br>"); echo(snippetwop("this is not too long to run on the column on the left,no idea") . "<br>"); echo(snippetgreedy("this is not too long to run on the column on the left,no idea")); */ /*** 来自:编程之家 jb51.cc(jb51.cc) ***/ ?>

猜你在找的PHP相关文章