dc95
dc95

Reputation: 1359

Truncating A php String for given Width in Pixels

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.

Upvotes: 0

Views: 674

Answers (2)

Mike Grabowski
Mike Grabowski

Reputation: 1965

As far as I understand from your question, you are trying to hide an overflow when the string is longer than container given?

I would rather suggest using overflow:hidden; white-space:nowrap; and maybe some text-overflow:ellipsis; to make "..." effect just before the end of container. But you have to remember, that fonts render differently through most browsers and operating systems, so the user experience might be different on Windows than on Mac.

Upvotes: 2

Eisa Adil
Eisa Adil

Reputation: 1733

That probably won't work. JS and PHP can't be mixed like that. The while loop is useless.

One solution that came to my mind is that you can first get the PHP string, through ajax, and then display it according to the width using JS.

Upvotes: 0

Related Questions