开发者

PHP> echo string separated by lines of 3 words each?

I need make something that includes a function that uses explode to create an array. I have seen several examples, but near the end I really get confused! Is there a simple readable way for this? (//comments?)

Take for instance a piece of text:

"This is a simple text I just created".

The output should look like this:

This is a
simple text I
开发者_高级运维just created 

So the explode should split the text into lines of 3 words each.


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


Try this is what you need:

<?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.' ';
}
?>

Result:

This is a
simple text I
just created 


Use substr() function link

Example:

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

In your case:

<?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
?>


explode just splits the string at a specified character. There's nothing more to it.

explode(',', 'Text,goes,here');

This splits the string whenever it meets a , and returns an array.

to split by a space character

explode(' ', 'Text goes here');

This splits only by a space character, not all whitespace. Preg_split would be easier to split by any whitespace


So something like...

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

Then all you have to is:

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

or

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

..depending if you just want new lines or if you want HTML output.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜