PHP> echo字符串由每个3个字的行分隔?

时间:2011-03-31 18:53:09

标签: arrays string echo explode

我需要制作包含使用explode创建数组的函数的东西。我已经看过几个例子,但接近结束时我真的很困惑!有一个简单的可读方式吗? (//注释?)

以一段文字为例:

"This is a simple text I just created".

输出应如下所示:

This is a
simple text I
just created 

所以爆炸应该将文本分成3个单词的行。

5 个答案:

答案 0 :(得分:1)

尝试这就是你需要的:

<?php

$text = "This is a simple text I just created";

$text_array = explode(' ', $text);

$i = 1; // I made change here :)
foreach($text_array as $key => $text){

 if(ceil(($key + 1) / 3) != $i) { echo "<br/>"; $i = ceil(($key + 1) / 3);  }
 echo $text.' ';
}
?>

结果:

This is a
simple text I
just created 

答案 1 :(得分:1)

$text = "This is a simple text I just created";
$text_array = explode(" ", $text);
$chunks = array_chunk($text_array, 3);
foreach ($chunks as $chunk) {
    $line = $impode(" ", $chunk);
    echo $line;
    echo "<br>";
}

答案 2 :(得分:0)

使用substr()函数link

示例:

<?php
$rest = substr("abcdef", -1);    // returns "f"
$rest = substr("abcdef", -2);    // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?>

在你的情况下:

<?php 
$rest = substr("This is a simple text I just created", 0, 15); //This will return first 15 characters from your string/text

echo $rest; // This is a simpl
?>

答案 3 :(得分:0)

explode只是将字符串拆分为指定的字符。没有更多的东西了。

爆炸(',','文字,去,在这里');

这会在遇到a时拆分字符串,并返回一个数组。

用空格分割

爆炸('','文字在这里');

这只能用空格字符分割,而不是所有空格。 Preg_split将更容易被任何空格分割

答案 4 :(得分:0)

就像......

function doLines($string, $nl){
  // Break into 'words' 
  $bits = explode(' ', $string);
  $output = '';
  $counter=0;
  // Go word by word...
  foreach($bits as $bit){
     //Add the word to the output...
     $output .= $bit.' ';
     //If it's 3 words...
     if($counter==2){
       // Remove the trailing space
       $output = substr($output, 0, strlen($output)-1);
       //Add the separator character...
       $output .=$nl;
       //Reset Counter
       $counter=0;
     }
  }
  //Remove final trailing space
  $output = substr($output, 0, strlen($output)-1);

  return $output;
}

然后你只需要:

echo doLines("This is a simple text I just created", "\n");

echo doLines("This is a simple text I just created", "<br />");

..取决于您是否只需要新行或是否需要HTML输出。