Excerpt isn't working with file contents
$excerpt= excerpt(file_get_contents("data/file.txt"), 30);
echo $excerpt;
function excerpt($str, $chars){
$index = strripos($str, ' ');
return substr($str, 0, $index)."...";
}
It don't return the text stripped at the 30 characters or less. It returns the whole text without the last word and the dots added but if you use a string typed manually it works p开发者_StackOverflow社区erfect.
Why this isn't working if content is loaded from a text file? I think that the /n's are broking the strripos.
You want to use stripos, not strripos.
<?php
$excerpt= excerpt(file_get_contents("data/file.txt"), 30);
echo $excerpt;
function excerpt($str, $chars){
$index = stripos($str, " ", $chars);
return substr($str, 0, $index)."...";
}
?>
The problem is not related to the stripos
usage. As I can see you're trying to trim the string at 30 characters without cutting words in half. In order to do that you need to correct your excerpt
function:
function excerpt($str, $chars) {
//no need to trim, already shorter than wanted dimension
if (strlen($tr) <= $chars) {
return $str;
}
//find last space within wanted dimension
$last_space = strrpos(substr($str, 0, $chars), ' ');
$trimmed_text = substr($str, 0, $last_space);
return $trimmed_text . '...';
}
and yes, your function doesn't even use the $chars param...
I gues you want an excerpt with as many whole words as possible. Some tips:
If you only just want the first 3o chars you should not read the whole file!
What you should do: read only to the maximum excerpt lenght and then format it.
function readExcerpt($path){
$fhand = fopen($path,"r");
$excerpt = fread($fhand ,30);
fclose($fhand);
return $excerpt;
}
function fromatExcerpt($excerpt){
//remove last word/word fragment
$index = strripos($excerpt,' ');
if($index!==false){
$excerpt= substr($excerpt,0,$index);
}
return $excerpt.'...';
}
echo fromatExcerpt(readExcerpt("D:\hotfix.txt"));
精彩评论