2012-04-15 56 views
0

我想只显示该段落的两行。
我该怎么做?回显部分文本

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

你需要更具体。 – 2012-04-15 15:28:02

+0

你可以借助插图。 – 2012-04-15 15:28:56

回答

0

试试这个:

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

和线路的可变数量,用途:

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

干杯!

1

取决于你是指文本内容,你也许可以用这脱身:

// `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]; 

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

+0

为什么不分裂“\ n”? – 2012-04-15 15:34:30

+0

@zol - 这是'nl2br()'函数的功能。 [来自手册](http://php.net/manual/en/function.nl2br.php),它表示它可以用于\ r \ n,\ n \ r,\ n和\ r' – Lix 2012-04-15 15:34:56

+0

nl2br不会拆分,它将转换... – 2012-04-15 15:52:45

1

如果你的意思的句子,你可以通过爆炸段落,并选择阵列的前两个部分来做到这一点:

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

否则,你将不得不在两行和使用计数的字符数一个substr()函数。例如,如果两行长度为100个字符,你会做:

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

然而,由于这样的事实:并不是所有的字体字符具有相同的宽度,可能难以准确地做到这一点。我建议采用最广泛的字符,例如'W',并在一行中回显多个这样的字符。然后计算可以跨两行显示的最大字符的最大数量。从这你会有最佳的数字。虽然这不会给你一个紧凑的两条线,但它将确保它不能超过两条线。

但是,这可能导致一个词被分成两部分。为了解决这个问题,我们可以使用爆炸函数来查找提取字符中的最后一个单词。

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

然后我们可以找到最后一个单词并从最终输出中删除正确数量的字符。

$numwords = count($array); 
$lastword = $array[$numwords]; 
$numchars = strlen($lastword); 
$2lines = substr($2lines, 0, (0-$numchars)); 
+0

@Lix抱歉,现在已修复。 – James 2012-04-15 15:36:17

+0

是的 - 想要删除我的投票,但分裂了“。”性格也是一个问题。如果字符串“Dr.Love”包含在文本中,该怎么办? – Lix 2012-04-15 15:37:01

+0

这就是为什么我建议使用substr代替。 – James 2012-04-15 15:38:25

0

这是一个比较普遍的答案 - 您可以使用此行取得任何数量:

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

你可以使用echo getLines($crow->content,2);做你想做什么。

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 
+0

再次阅读OP - 他只想返回前两行。 – Lix 2012-04-15 15:48:17

+1

@Lix修复它。想要删除您的投票吗? – Sawny 2012-04-15 15:50:31

+0

您可能还想重新阅读您的评论专栏:)编辑后他们没有多大意义... – Lix 2012-04-15 15:51:50