我在数据库中有一段类似
$str="这是我很快显示的一段,当我点击更多视图时,它将完全显示我正在使用ajax并检索它"
我像一样显示这个
这是我很快展示的一段
php显示第一个单词是
function chop_string($str, $x)// i called the function
{
$string = strip_tags(stripslashes($string));
return substr($string, 0, strpos(wordwrap($string, $x), "'n"));
}
当用户点击view more
时,它将显示其剩余部分,但问题是如何跳过该this is a paragraph i show shortly
并显示其剩余的
我想在点击view more
时显示$x
之后的段落
用于按单词数量的字符截断字符串:
- 这个SO问题可能会有所帮助
- 就像这次一样
- 这里有一些代码专门通过字数来实现这一点
就点击链接时显示更多文本而言,我建议从数据库中一次性加载字符串并格式化其输出。如果你的字符串是:
这是从我的数据库中提取的整个字符串。
然后以下代码将被格式化为这样:
HTML
<p class="truncate">This is the whole string <a class="showMore">Show more...</a><span> pulled from my database.</span></p>
CSS
p.truncate span { display: none; }
这样,您就可以使用Javascript(最好是通过我为下面的代码选择的jQuery这样的库)来隐藏或显示更多的解决方案,而不必使用AJAX进行第二次数据库请求。以下Javascript可以满足您的要求:
$("a.showMore").on("click", function() {
$(this).parent().find("span").contents().unwrap();
$(this).remove();
});
这是一把小提琴!
我在这里举了一个例子:shaquin.tk/experiments/showmore.html.
您可以查看源代码以查看其背后的所有代码。PHP代码显示在页面上。
如果您不想在单击Show more
时显示起始字符串,请将JavaScript函数showMore
替换为:
function showMore() {
if(state == 0) {
state = 1;
document.getElementById('start').style.display = 'none';
document.getElementById('end').style.display = 'block';
document.getElementById('showmore').innerHTML = 'Show less';
document.getElementById('text-content').className = 'expanded';
document.getElementById('start').className = 'expanded';
} else {
state = 0;
document.getElementById('start').style.display = 'block';
document.getElementById('end').style.display = 'none';
document.getElementById('showmore').innerHTML = 'Show more';
document.getElementById('text-content').className = '';
document.getElementById('start').className = '';
}
}
希望这能有所帮助。
使用此函数:
function trim_text($string, $word_count)
{
$trimmed = "";
$string = preg_replace("/'040+/"," ", trim($string));
$stringc = explode(" ",$string);
//echo sizeof($stringc);
//echo " words <br /><br />";
if($word_count >= sizeof($stringc))
{
// nothing to do, our string is smaller than the limit.
return $string;
}
elseif($word_count < sizeof($stringc))
{
// trim the string to the word count
for($i=0;$i<$word_count;$i++)
{
$trimmed .= $stringc[$i]." ";
}
if(substr($trimmed, strlen(trim($trimmed))-1, 1) == '.')
return trim($trimmed).'..';
else
return trim($trimmed).'...';
}
}
$wordsBefore = 3;
$numOfWords = 7;
implode(' ', array_slice(explode(' ', $sentence), $wordsBefore, $wordsBefore+$numOfWords));
如果将句子保存到一个变量命名的句子中,这将返回句子的前7个单词。