4

I created a variable which stores a very long string, and I want to print this variable in multiple lines.

$test ="This is some example text , I want to print this variable in 3 lines";

The output of the above $test would be

This is some example text,
I want to print this
variabale in 3 lines

Note: I want a new line after each 15 characters or each line have equal characters. I don't want to add break tag or any other tag during variable assignment.

web dev
  • 305
  • 1
  • 5
  • 17

5 Answers5

7

CODEPAD

<?php
$str=  'This is some example text , I want to print this variable in 3 lines, also.';
$x = '12';
$array = explode( "\n", wordwrap( $str, $x));
var_dump($array);
?>

or use

$array = wordwrap( $str, $x, "\n");
Prashant Tapase
  • 2,132
  • 2
  • 25
  • 34
2

Try This

<?php
$test ="This is some example text , I want to print this variable in 3 lines";
$explode=explode(" ",$test);
$String='';
$newString='';
$maxCharacterCount=23;
foreach ($explode as $key => $value) {
    $strlen=strlen($String);
    if($strlen<=$maxCharacterCount){
            $String.=' '.$value;

        }else{
            $newString.=$String.' '.$value.'<br>';
            $String='';

        }
     }
     $finalString= $newString.$String;
     echo $finalString;
?>
daulat
  • 969
  • 11
  • 24
2

Try this

 <?php 
    $test ="This is some example text , I want to print this variable in 3 lines";
    $array = str_split($test, 10); 

    echo implode("<br>",$array);

Based on this link PHP: split a long string without breaking words

$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.';

$arrayWords = explode(' ', $longString);

// Max size of each line
$maxLineLength = 18;

// Auxiliar counters, foreach will use them
$currentLength = 0;
$index = 0;

foreach($arrayWords as $word)
{
    // +1 because the word will receive back the space in the end that it loses in explode()
    $wordLength = strlen($word) + 1;

    if( ( $currentLength + $wordLength ) <= $maxLineLength )
    {
        $arrayOutput[$index] .= $word . ' ';

        $currentLength += $wordLength;
    }
    else
    {
        $index += 1;

        $currentLength = $wordLength;

        $arrayOutput[$index] = $word;
    }
}
Community
  • 1
  • 1
  • Thanks, It works for me. – web dev Jul 24 '15 at 07:36
  • @SadamAfridi You don't matter if it cuts a word in 2 lines ? – Random Jul 24 '15 at 07:37
  • Yes , this is still an issue but it would be difficult to prevent from breaking the word in two lines, do you have any solution? @random – web dev Jul 24 '15 at 07:45
  • Prashant's solution doesn't cut words. And you can define max line length (here 12 characters max) – Random Jul 24 '15 at 08:04
  • @SadamAfridi with the edits, now both should work... Can't understand what happen about edits... Prashant's solution is in error's answer now... Strange things happen here... :) – Random Jul 24 '15 at 08:14
2

The easiest solution is to use wordwrap(), and explode() on the new line, like so:

$array = explode( "\n", wordwrap( $str, $x));

Where $x is a number of characters to wrap the string on. Copied from here last comment

Community
  • 1
  • 1
web dev
  • 305
  • 1
  • 5
  • 17
1

OK now all is working. You just pass $string and @maxlenght in characters number and function returns table with cutted string.

  • don`t cut words,
  • don`t ever exeed maxLenght,

Only one thing to rember is that u need to care for comma usage i.e: "word, word".

$test ="This is some example text, I want to print this variable in 3 lines dasdas das asd asd asd asd asd ad ad";

function breakString($string, $maxLenght) {

    //preparing string, getting lenght, max parts number and so on
$string = trim($string, ' ');
$stringLenght = strlen($string);
$parts = ($stringLenght / $maxLenght );
$finalPatrsNumber = ceil($parts);   
$arrayString = explode(' ', $string);
    //defining variables used to store data into a foreach loop
$partString ='';
$new = array();
$arrayNew = array();

   /**
    * go througt every word and glue it to a $partstring
    * 
    * check $partstring lenght if it exceded $maxLenght 
    * then delete last word and pass it again to $partstring
    * and create now array value
    */

foreach($arrayString as $word){
    $partString.=$word.' ';

    while(  strlen( $partString ) > $maxLenght) {
        $partString = trim($partString, ' ');
        $new = explode(' ', $partString);
        $partString = '';
        $partString.= end($new).' ';  
        array_pop($new);
        //var_dump($new);
        if( strlen(implode( $new, ' ' )) < $maxLenght){
            $value = implode( $new, ' ' );
            $arrayNew[] = $value;
        }        
    }    
}

//    /**
//    * psuh last part of the string into array
//    */
$string2 = implode(' ', $arrayNew);


$string2 = trim($string2, ' ');
$string2lenght = strlen($string2);
$newPart = substr($string, $string2lenght);
$arrayNew[] = $newPart;

  /**
   * return array with broken $parts of $string 
    * $party max lenght is < $maxlenght 
    * and breaks are only after words
   */
return $arrayNew;

}

   /**
    * sample usage
    * @param string $string
    * @param int $maxLenght Description
    */

foreach( breakString($test, 30) as $line){
    echo $line."<br />";
}

displays:

This is some example text, I
want to print this variable
in 3 lines dasdas das asd asd
asd asd asd ad ad

btw. u can easly add here some rules like:

  • no single char in last row or don`t break on certain words and so on;
fsn
  • 549
  • 3
  • 11