php 不破坏单词截取字符串的解决办法
内容摘要
这篇文章主要为大家详细介绍了php 不破坏单词截取字符串的简单示例,具有一定的参考价值,可以用来参考一下。
对此感兴趣的朋友,看看idc笔记做的技术笔记。经测试代码如下:
<?ph
对此感兴趣的朋友,看看idc笔记做的技术笔记。经测试代码如下:
<?ph
文章正文
这篇文章主要为大家详细介绍了php 不破坏单词截取字符串的简单示例,具有一定的参考价值,可以用来参考一下。
对此感兴趣的朋友,看看idc笔记做的技术笔记。经测试代码如下:<?php
/**
* 截取字符串
*
* @param
* @arrange (www.idcnote.com)
* 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,0,$length) . $tail;
}
}
$text = substr($text,0,$length-$i+1) . $tail;
}
return $text;
}
// It behaves greedy, gets length characters ore goes for more
function snippetgreedy($text,$length=64,$tail="...") {
$text = trim($text);
if(strlen($text) > $length) {
for($i=0;$text[$length+$i]!=" ";$i++) {
if(!$text[$length+$i]) {
return $text;
}
}
$text = substr($text,0,$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=64,$tail="...") {
$text = trim($text);
$txtl = strlen($text);
if($txtl > $length) {
for($i=1;$text[$length-$i]!=" ";$i++) {
if($i == $length) {
return substr($text,0,$length) . $tail;
}
}
for(;$text[$length-$i]=="," || $text[$length-$i]=="." || $text[$length-$i]==" ";$i++) {;}
$text = substr($text,0,$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, perhaps, or perhaps yes, no idea") . "<br>");
echo(snippetgreedy("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea"));
*/
/*** 来自:php教程(www.idcnote.com) ***/
?>
注:关于php 不破坏单词截取字符串的简单示例的内容就先介绍到这里,更多相关文章的可以留意
代码注释