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

Asked

Viewed 149 times

3

I need it for some conditional ties, but I have no idea how to do it, or if it’s possible.

Supposing I have a string, and I need to know how many lines it would take in a given paragraph (<p>), only it cannot be calculated in front-end (js), it has to be in back, in php.

Does anyone know a function where I can pass the Width size plus the string, and it returns the total of lines?

something like

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

In case it’s not very clear, please ask that I try to clarify.

  • 3

    The simplified answer is no, it does not because you have no control over the end-user’s source settings. In practice, you could even estimate if you use the same source on the server and simulate a render of it, and this if you already know the final width of the <p> when rendering on the client side, but it is far from being a simple task. It is immense the amount of things that can get out of your control in this process, starting with each browser’s ability to have variation. A pixel difference in each case can totally change the place of automatic line breaks.

  • substr_count($texto, "\n")?

  • I didn’t think I would, but it wouldn’t hurt to try, right? I thought of another solution to my problem. Thanks, guys!

1 answer

3


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

With this you can have a very close and sometimes exact result, but you can never trust.

One of the reasons to avoid this type of solution is that you will not have control on the client side. A user may not have the font-family and then the browser takes the next one from the list or a default font which will probably have different measures.

inserir a descrição da imagem aqui

If you still want to proceed, you can start with the functions of the GD library: http://www.php.net/manual/en/function.imagettfbbox.php

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 above script shows disregards this and may be breaking a word. If this is not what you want, you will have to create an implementation that identifies the spacing. It is not very difficult, but it is a bit complicated. The above example is enough.

  • I will include the source in the document. This helps, no?

  • It also does not guarantee but it is safer. I say that it does not guarantee because it can also occur that the source is not loaded. Then everything is screwed.

  • I’m going to study that function you mentioned. I thought of using it to calculate the size of each word, and when the sum of them (plus the spaces) reaches or passes the informed width, the function increments +1 to $lines. Does it work?

  • 1

    Yes. It’s very simple. I’ll put an easy example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.