Reputation: 446
I am attempting to write my first custom function. I understand that there are other functions out there that do the same thing that this does, but this one is mine. I have the function wrote, but I do not understand char_list as it pertains to functions and cannot figure out the third parameter of the str_word_count function in php. I think I need to this in a certain format to maintain periods, comma, semi-colons, colons, etc. Please note that double and single quotes are maintained throughout the function. It is bottom symbols that are strip from the string.
$text = "Lorem ipsum' dolor sit amet, consectetur; adipiscing elit. Mauris in diam vitae ex imperdiet fermentum vitae ac orci. In malesuada."
function textTrim($text, $count){
$originalTxtArry = str_word_count($text, 1);
$shortenTxtArray = str_word_count(substr(text, 0,$count), 1);
foreach ($shortenTxtArray as $i=>$val) {
if ($originalTxtArry[$i] != $val) {
unset($shortenTxtArray[$i]);
}
}
$shortenTxt = implode(" ", $shortenTxtArray)."...";
return $shortenTxt;
}
Output Lorem ipsum' dolor sit amet consectetur adipiscing elit Mauris in diam...
Notice the "," after amet is missing.
Ignore the string of periods at the end, I concatenate those on to the end before the return
Thank You for all assistance.
Dave
Upvotes: 1
Views: 789
Reputation: 9
<?php
function trimTxt($str, $limit){
/** remove consecutive spaces and replace with one **/
$str = preg_replace('/\s+/', ' ', $str);
/** explode on a space **/
$words = explode(' ', $str);
/** check to see if there are more words than the limit **/
if (sizeOf($words) > $limit) {
/** more words, then only return on the limit and add 3 dots **/
$shortTxt = implode(' ', array_slice($words, 0, $limit)) . 'content here';
} else {
/** less than the limit, just return the whole thing back **/
$shortTxt = implode(' ', $words);
}
return $shortTxt;
}
?>
Upvotes: -1
Reputation: 2877
Updated function to explode based on a space
function textTrim($str, $limit){
/** remove consecutive spaces and replace with one **/
$str = preg_replace('/\s+/', ' ', $str);
/** explode on a space **/
$words = explode(' ', $str);
/** check to see if there are more words than the limit **/
if (sizeOf($words) > $limit) {
/** more words, then only return on the limit and add 3 dots **/
$shortenTxt = implode(' ', array_slice($words, 0, $limit)) . '...';
} else {
/** less than the limit, just return the whole thing back **/
$shortenTxt = implode(' ', $words);
}
return $shortenTxt;
}
Upvotes: 2
Reputation: 4265
From the PHP manual about the third parameter, charlist:
A list of additional characters which will be considered as 'word'
These are any characters outside the usual a-z which should be included as part of a word, and not causing a word to break.
If you look at example 1 on the PHP manual you linked to, it will show an example where the word 'fri3nd' is only classed as 1 word when 3 is included in the charlist parameter.
Upvotes: 0