Home » Php » Split a text into two columns with PHP

Split a text into two columns with PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

I would like to know if there is possible to split a text in two parts.

On my website I have a product description (500-1000 words) and I would like to display it like so:

<div class="text-col">
    <?php echo nl2br($col1); ?>
</div>


<div class="text-col">
    <?php echo nl2br($col2); ?>
</div>
How to&Answers:

Something like this?

$len = strlen($input);
$space = strrpos($input," ",-$len/2);
$col1 = substr($input,0,$space);
$col2 = substr($input,$space);
// now output it

Answer:

This in IMHO a typical issue which should be done via CSS, because it only affects how it is displayed. Why don’t you use CSS3’s column-count:

div#multicolumn1 {
  -moz-column-count: 3;
  -moz-column-gap: 20px;
  -webkit-column-count: 3;
  -webkit-column-gap: 20px;
  column-count: 3;
  column-gap: 20px;
}

(Copied from http://www.quirksmode.org/css/multicolumn.html)

Answer:

You can easily split a text in two part in PHP :

$text = "my very long text with a lot of words";
$length = strlen($text);
$middle = round($length/2, 0);
$col1 = substr($text, 0, $middle);
$col2 = substr($text, $middle);

But this mots often cut the phrase in the middle of a word. So you’ll need to update the code to find the nearest space of the middle :

for ($i = $middle; $i < $length; $i ++) {
    if ( substr($text, $i, 1) == " " ) return;
}
$cut = $i;
$col1 = substr($text, 0, $cut);
$col2 = substr($text, $cut+1);

The space is not the only place for a nice text cut. So, you will have to look for the ends of line. And some spaces are not good either. For example the space juste before a semi-colon. So you will add to improve this code for improved results.

You can also try the css3 multi-column directive :
http://www.css3.info/preview/multi-column-layout/
but it’s note supported by IE.

Answer:

It’s as easy as:

$text = "This should be a very long product description with some bold specs in it.";
$splitat = strpos($text," ",strlen($text)/2);
$col1 = substr($text, 0, $splitat);
$col2 = substr($text, $splitat);

But in reality you might want to do it client-side, since there might be other factors involved, light paragraph width, hyphenation, text block height, etc.

In CSS3 you already have support for multiple columns of text.

Answer:

Can you use wordwrap() function?