0

I want to print specific word character in specific Line (do something like a word wrap)

Suppose I have 40 Character.

My Name Is Johnty and i am eating an Nut

and my length for character is 20.

So in First Line I want to Print 20 character but if it will break the word than whole word will print in next line.

For Example , i have 20 character length in first line than don't print like this :

First Line : My Name Is Johnty an
Second Line : d i am eating an Nut

Instead, I want following output :

First Line : My Name Is Johnty
Second Line : and i am eating an 
Third Line : Nut

So How to do this in Simple PHP ??

Thanks in Advance

progyammer
  • 1,498
  • 3
  • 17
  • 29
Sachin Sanchaniya
  • 996
  • 1
  • 8
  • 16

2 Answers2

2

wordwrap — Wraps a string to a given number of characters . wordwrap

<?php
    $text = "My Name Is Johnty and i am eating an Nut";
    $newtext = wordwrap($text, 20, "<br />\n");

    echo $newtext;
    ?>

OUTPUT:

My Name Is Johnty
and i am eating an
Nut

EDIT 1:

YES, You can save it in Variable after Split the String. You must be use explode() with inside of wordwrap() methods to do this things.

      $strText = "My Name Is Johnty and i am eating an Nut"; //here ur string 
         // Wrap lines limited to 20 characters and break
         // them into an array
      $lines = explode("\n", wordwrap($strText, 20, "\n"));
      var_dump($lines);
      $one=$lines;
      print_r($one[0]);

OUTPUT:

for $one[0],

My Name Is Johnty

for $one[ 1 ],

and i am eating an
Karthi
  • 528
  • 1
  • 5
  • 16
0

By using the wordwrap() you can wrap the characters within the words.

Example:

$string = "My Name Is Johnty and i am eating an Nut";
echo wordwrap($string, 20, "<br />\n")

Output:

My Name Is Johnty
and i am eating an
Nut

Details about the- wordwrap() in http://php.net/.

Updates:

$string = "My Name Is Johnty and i am eating an Nut";
$arr = explode(PHP_EOL, wordwrap($string, 20, "\n\r"));

print_r($arr);
Murad Hasan
  • 9,565
  • 2
  • 21
  • 42