限制内容的字符

时间:2012-12-19 01:35:19

标签: php

我有内容,我试图限制使用此查询:

if(strlen($news_content < 35)){
         $news_content = substr($news_content, 0, 30) . "";
    }

但由于某种原因,它并没有限制字符..或者这是我的编码(我确定它为什么不起作用),这有点偏。

这是完整的代码:

<?php

    $amount_get = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "'"); 
    $comments = mysql_num_rows($amount_get);            

    $grab = mysql_query("SELECT * FROM articles WHERE id='" . mysql_real_escape_string($_GET['id']) . "' LIMIT 1");    
    $grab = mysql_query("SELECT id, news_title, news_content, news_author, news_day, news_month, news_year, news_date FROM articles ORDER BY id DESC limit 3"); 
    $news_day =$row['news_day'];
    $news_month =$row['news_month'];
    $news_year =$row['news_year'];
    $news_content =$row['news_content'];

    if(strlen($news_content < 35)){
                        $news_content = substr($news_content, 0, 30) . "";
                    } 

    elseif (mysql_num_rows($grab)==0) {
    echo "<div class='alert alert-note-x'>Sorry, it looks like their are no articles posted!</div>";
}
    while($row = mysql_fetch_array($grab)){

?>

<div class="post-container">
    <div class="post">
    <div class="left">
    <div class="date"><span class="day"><?php echo $row['news_day'] ?></span> <span class="month"><?php echo $row['news_month'] ?></span> <span class="year"><?php echo $row['news_year'] ?></span></div></div>
    <div class="postcontent"><h5 class="posttitle"><a href="#/media/<?php echo $row['id'] ?>.<?php echo stripslashes(str_replace(" ", "-", $row['news_title'])); ?>"><?php echo stripslashes($row['news_title']); ?></a></h5>                       

        <?php echo $row['news_content'] ?>
        <p> (READ MORE)</p>
        <p>Comments (<?php echo $comments ?>)</p>
        </div>
</div>​
</div>  
  

我只是想限制“news_content”,但我不知道我在哪里搞砸了。谢谢!

3 个答案:

答案 0 :(得分:2)

尝试更改第一行:

if(strlen($news_content < 35)) {...}

要:

if(strlen($news_content) > 35) {

这包括将<切换为>,因为如果长度超过35个字符而不是更少,您可能希望截断?

我认为通常有更好的方法来截断。你的方法可能只是在一个单词的中间突然切断文本。有关其他想法,请查看http://www.the-art-of-web.com/php/truncate/#.UNEbnmdaerIhttp://www.ambrosite.com/blog/truncate-long-titles-to-the-nearest-whole-word-using-php-strrpos

答案 1 :(得分:1)

在html代码中,您不能引用<?php echo $news_content?>,而是<?php echo $row['news_content']?>,因此忽略了缩短版本。

将其与建议的更改相结合,将strlen($row['news_content']) < 35更改为> 35以使其正常运行。

答案 2 :(得分:-1)

以下应该工作:

if (strlen($news_content) < 35))