Modify a php limit text function adding some kind of offset to it
- by webmasters
Maybe you guys can help:
I have a variable called $bio with bio data.
$bio = "Hello, I am John, I'm 25, I like fast cars and boats. I work as a blogger and I'm way cooler then the author of the question";
I search the $bio using a set of functions to search for a certain word, lets say "author" which adds a span class around that word, and I get:
$bio = "Hello, I am John, I'm 25, I like fast cars and boats. I work as a blogger and I'm way cooler then the <span class=\"highlight\">author</span> of the question";
I use a function to limit the text to 85 chars:
$bio = limit_text($bio,85);
The problem is when there are more then 80 chars before the word "author" in $bio.
When the limit_text() is applied, I won't see the highlighted word author.
What I need is for the limit_text() function to work as normal, adding all the words that contain the span class highlight at the end.
Something like this:
*"This is the limited text to 85 chars, but there are no words with the span class highlight so I am putting to be continued ... **author**, **author2** (and all the other words that have a span class highlight around them separate by comma "*
Hope you understood what I mean, if not, please comment and I'll try to explain better.
Here is my limit_text() function:
function limit_text($text, $length){ // Limit Text
if(strlen($text) > $length) {
$stringCut = substr($text, 0, $length);
$text = substr($stringCut, 0, strrpos($stringCut, ' '));
}
return $text;
}
UPDATE:
$xturnons = str_replace(",", ", ", $xturnons);
$xbio = str_replace(",", ", ", $xbio);
$xbio = customHighlights($xbio,$toHighlight);
$xturnons = customHighlights($xturnons,$toHighlight);
$xbio = limit_text($xbio,85);
$xturnons = limit_text($xturnons,85);
The customHighlights function which adds the span class highlighted:
function addRegEx($word){ // Highlight Words
return "/" . $word . '[^ ,\,,.,?,\.]*/i';
}
function highlight($word){
return "<span class='highlighted'>".$word[0]."</span>";
}
function customHighlights($searchString,$toHighlight){
$searchFor = array_map('addRegEx',$toHighlight);
$result = preg_replace_callback($searchFor,'highlight',$searchString);
return $result;
}