I want to truncate a given string taken from MySQL database through PHP to fit within given pixels. Most of the solutions I found were based on number of characters. But I specifically want it according to pixel length.(I don't want to use monospace font)
I found out that $('#idName').width()
can be used in JavaScript for fitting. And that works fine with strings written in HTML simply. But here is the deal. My string is a variable stored in PHP, I need JavaScript to get width in pixels and I need to have that string in a span (in HTML) with specific id name.
So, I have tried to make it work using all three of them- PHP, HTML and JavaScript. Below is my code.
<?php
$len=100;
?>
<span id='d' style="display:none;"><?php echo substr($details,0,$len) ?></span>
<script>
var len=370;
while($('#d').width()>len){
<?php
$len=$len-1;
echo "<span id='d' style='display:none;'>" . substr($details,0,$len) . "</span>";
?>
}
<?php echo substr($details,0,$len); ?>
</script>
So I take my string's first 100 letters and put them in a span with id d
. Then in JavaScript, I get its width and check in while loop. I run while loop (keep decreasing $len
) until the pixel length of the substring is within desired width and keep redifining that substring in span with same id. Then I print that substring.
Could someone please change the code to make it work or suggest a better method? I am newbie in this, so please make it as simple as you can.