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.
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");
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With