我想为文章介绍创建一个方法,该方法将打破空格,逗号,句点,分号,问号或感叹号上的返回文本。 我被困在这段代码中:
function getIntro($count = 200) {
return substr(strip_tags($this->content), 0, $count) . '...';
}
请告诉我如何使用我的函数做到这一点?
function splitAtBlank($string, $tryToSplitAt){
$string = substr($string, 0, $tryToSplitAt);
$i = strlen($string);
$i--;
while($string[$i] != " " && $i > 0){
$i--;
}
return substr($string, 0, $i);
}
然后你可以简单地使用它:
echo splitAtBlank("Your string", 8);
为了您的目的:
function getIntro($count = 200) {
$string = substr(strip_tags($this->content), 0, $count);
$i = strlen($string);
$i--;
while($string[$i] != " " && $i > 0){
$i--;
}
return substr($string, 0, $i) . '...';
}
另一个版本来处理多个分隔符:
function getIntro($count = 200){
$chars = array(' ', '.', ',', '!', '?');
$string = substr(strip_tags($this->content), 0, $count);
$i = strlen($string) - 1;
while(!in_array($string[$i], $chars) && $i > 0){
$i--;
}
return substr($string, 0, $i) . '...';
}
如果你的文章里有一些HTML标签,你应该在拆分之前使用strip_tags()
。如果您需要处理标签打开/关闭状态,请评论这篇文章。
如果要查找位置 200 之前最近的空格、逗号、句点、分号、问号或感叹号,则必须查找所有这些并获取大部分可用的文本。
因此,如果您的文本是:
$text='"读者会分心是一个早已确定的事实 通过查看布局时页面的可读内容?这 使用Lorem Ipsum的要点是它或多或少具有法线 分布",我希望我的函数能让介绍停止在单词正常, 而不是停留在单词分发然后切割,它';
//cut the string at 200
$cut_text=substr($text,0,200);
//look for all these characters.
//strripos returns the position of the last occurrance of the character
$needles=array(' ','.',',','?','!',';');
foreach($needles as $needle){
$pos[]=strripos($cut_text,$needle);
}
//sort the array to get the biggest 'position'. The biggest is $pos[0]
rsort($pos);
//look if there is found a match, if not: just take the 200 characters
if(empty($pos[0])){$result=$cut_text;}
else{
$result=substr($cut_text,0,$pos[0]);
}
echo $result;
在示例中,它紧接着剪切文本
或多或少正常