也许你们可以帮忙:
我有一个名为 $bio 的变量,其中包含生物数据。
$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";
我使用一组函数搜索 $bio 来搜索某个单词,比如说“作者”,它在该单词周围添加了一个 span 类,我得到:
$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";
我使用一个函数将文本限制为 85 个字符:
$bio = limit_text($bio,85);
问题是当$bio中的“作者”一词之前有超过 80 个字符时。应用时,我不会看到突出显示的词作者。limit_text()
我需要让 limit_text() 函数正常工作,在最后添加包含 span 类突出显示的所有单词。像这样的东西:
*"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 "*
希望您理解我的意思,如果没有,请发表评论,我会尽力解释得更好。
这是我的limit_text()
功能:
function limit_text($text, $length){ // Limit Text
if(strlen($text) > $length) {
$stringCut = substr($text, 0, $length);
$text = substr($stringCut, 0, strrpos($stringCut, ' '));
}
return $text;
}
更新:
$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);
添加 span 类的customHighlights
函数突出显示:
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;
}