0

我只想显示段落的两行。
我该怎么做呢 ?

<p><?php if($display){ echo $crow->content;} ?></p>
4

5 回答 5

2

根据您所指的文本内容,您可能可以摆脱这种情况:

// `nl2br` is a function that converts new lines into the '<br/>' element.
$newContent = nl2br($crow->content);

// `explode` will then split the content at each appearance of '<br/>'.
$splitContent = explode("<br/>",$newContent);

// Here we simply extract the first and second items in our array.
$firstLine = $splitContent[0];
$secondLine = $splitContent[1];

注意- 这将破坏您在文本中的所有换行符!如果您仍想以原始格式保留文本,则必须再次插入它们。

于 2012-04-15T15:28:01.807 回答
1

如果你的意思是句子,你可以通过分解段落并选择数组的前两部分来做到这一点:

$array = explode('.', $paragraph);
$2lines = $array[0].$array[1];

否则,您将不得不计算两行的字符数并使用 substr() 函数。例如,如果两行的长度是 100 个字符,你会这样做:

$2lines = substr($paragraph, 0, 200);

However due to the fact that not all font characters are the same width it may be difficult to do this accurately. I would suggest taking the widest character, such as a 'W' and echo as many of these in one line. Then count the maximum number of the largest character that can be displayed across two lines. From this you will have the optimum number. Although this will not give you a compact two lines, it will ensure that it can not go over two lines.

This is could, however, cause a word to be cut in two. To solve this we are able to use the explode function to find the last word in the extracted characters.

$array = explode(' ', $2lines);

We can then find the last word and remove the correct number of characters from the final output.

$numwords = count($array);
$lastword = $array[$numwords];
$numchars = strlen($lastword);
$2lines = substr($2lines, 0, (0-$numchars));
于 2012-04-15T15:29:39.803 回答
1
function getLines($text, $lines)
{
    $text = explode("\n", $text, $lines + 1); //The last entrie will be all lines you dont want.
    array_pop($text); //Remove the lines you didn't want.

    return implode("<br>", $text); //Implode with "<br>" to a string. (This is for a HTML page, right?)
}

echo getLines($crow->content, 2); //The first two lines of $crow->content
于 2012-04-15T15:45:42.093 回答
0

This is a more general answer - you can get any amount of lines using this:

function getLines($paragraph, $lines){
    $lineArr = explode("\n",$paragraph);
    $newParagraph = null;
    if(count($lineArr) > 0){
        for($i = 0; $i < $lines; $i++){
            if(isset($lines[$i]))
                $newParagraph .= $lines[$i];
            else
                break;
        }
    }
    return $newParagraph;
}

you could use echo getLines($crow->content,2); to do what you want.

于 2012-04-15T15:36:23.307 回答
0

Try this:

$lines = preg_split("/[\r\n]+/", $crow->content, 3);
echo $lines[0] . '<br />' . $lines[1];

and for variable number of lines, use:

$num_of_lines = 2;
$lines = preg_split("/[\r\n]+/", $crow->content, $num_of_lines+1);
array_pop($lines);
echo implode('<br />', $lines);

Cheers!

于 2012-04-15T16:18:23.877 回答