Is it possible to know the number of lines that a text occupies in a p?

3

I need this for some conditional loops, but I have no idea how to do it, or if it's possible.

Assuming I have a string , and I need to know how many rows it would occupy in a given paragraph ( <p> ), only that can not be computed in the front end (js), it has to be in the back, in the php.

Does anyone know a function in which I can pass the Width size plus the string, and does it return the total of rows?

something like

<?php 
   function nmrLinhas(width, string){
         (faz o processo) 
        return linhas; 
   }
?>

If it is not very clear, please ask me what I will try to clarify.

    
asked by anonymous 01.02.2017 / 00:16

1 answer

3

For this task you will have to calculate the font family boundbox and measure the proportions by scale according to the width of the HTML element.

This may have a very close and sometimes accurate result, but you can never trust it.

One of the reasons for avoiding this kind of solution is that you will not have control of the client side. A user may not have the font-family and then the browser assumes the next one in the list or a default font which will probably have different measures.

  

Ifyoustillwanttoproceed,youcanstartwiththefunctionsoftheGDlibrary: link

Practical example:

/*
Largura do elemento HTML <p>
Defina em pontos (pt), não em pixels (px)
O motivo é que ficará complicado se definir em pixels porque a função imagettfbbox() retorna em pontos (pt).
*/
$p_width = 100; // em pontos, não em pixels

/*
Local da fonte:
*/
$font = './Arial_n.ttf';

/*
O texto
*/
$data = 'lorem ipsum a
sa odfdsgoi jgiodfg diofgjd foigd a
d fgidfogjdfio g';

/*
O primeiro parâmetro é o tamanho do texto, aqui definido em 16.
O segundo é o ângulo. Definido em zero pois será exibido na horizontal.
O terceiro é o arquivo da font-family. Aqui usei "Arial Normal".
O quarto é o texto.
*/
$bbox = imagettfbbox(16, 0, $font, $data);

/*
Exibe a largura maior encontrada.
Nesse exemplo, é 306pt
*/
echo 'texto largura: '.$bbox[2].'pt'.PHP_EOL;

/*
Arredonde o valor da divisão para cima pois se passar 0.01pt, indica que ultrapassou a linha corrente.
*/
echo 'linhas estimadas: '.ceil($bbox[2] / $p_width);

This is still insufficient because languages based on the Roman alphabet have spacing between words. The measures that the script above shows disregard this and may be breaking a word. If this is not what you want, you will need to create an implementation that identifies the spacing. It's not very difficult, but it's a bit complicated. The above example is enough.

    
01.02.2017 / 00:29