如何通过php跳过段落中的某些单词

时间:2012-07-09 04:22:15

标签: php javascript mysql html css

我在数据库中有一个类似的段落

  

$ str =“这是我即将展示的一段,当我点击视图时,它会完全显示我正在使用ajax并检索它”

我表现得像

  

这是我即将展示的一段

php for show第一个单词是

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并显示其余部分

我希望在点击$x

view more后显示段落

4 个答案:

答案 0 :(得分:5)

按字数量字符截断字符串:

  1. SO question可能会有所帮助。
  2. this one一样。
  3. Here's some code通过字数统计来实现。
  4. 就点击链接显示更多文本而言,我建议从数据库中加载一次字符串并格式化它的输出。如果你的字符串是:

      

    这是从我的数据库中提取的整个字符串。

    然后,下面的代码将被格式化为:

    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();
    });
    

    Here's a fiddle to play with!

答案 1 :(得分:2)

我在这里做了一个例子: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 = '';
    }
}

希望这有帮助。

答案 2 :(得分:1)

使用此功能:

function trim_text($string, $word_count)
{
   $trimmed = "";
   $string = preg_replace("/\040+/"," ", trim($string));
   $stringc = explode(" ",$string);
   //echo sizeof($stringc);
   //echo "&nbsp;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).'...';
   }
}

答案 3 :(得分:0)

$wordsBefore = 3;
$numOfWords = 7;
implode(' ', array_slice(explode(' ', $sentence), $wordsBefore, $wordsBefore+$numOfWords));

如果将句子保存到名为sentence的变量,这将返回句子的前7个单词。