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.
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.
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.
– Bacco
substr_count($texto, "\n")
?– Wallace Maxters
I didn’t think I would, but it wouldn’t hurt to try, right? I thought of another solution to my problem. Thanks, guys!
– Seu Madruga