Split text into two columns using PHP

I would like to know if it is possible to split the text into two parts.

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

<div class="text-col"> <?php echo nl2br($col1); ?> </div> <div class="text-col"> <?php echo nl2br($col2); ?> </div> 
+6
source share
5 answers

Something like that?

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

This is IMHO a typical problem that needs to be done through CSS, because it only affects how it is displayed. Why don't you use CSS3 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 )

+7
source

You can easily split the text into two parts 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 these motives often shorten the phrase in the middle of the word. Therefore, you will need to update the code to find the nearest space in 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); 

Space is not the only place for beautiful text. So you have to look for the ends of the line. And some spaces are not good either. For example, a space before a comma. Therefore, you will improve this code to improve results.

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

+1
source

It's simple:

 $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 fact, you can do this on the client side, as there may be other factors: paragraph width, hyphen, text block height, etc.

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

0
source

Can you use the wordwrap () function?

0
source

Source: https://habr.com/ru/post/913792/


All Articles