0

I am using the following PHP code to display a set of ellipses directly after 220 characters have displayed on-screen from the description field in a MySQL database.

...echo "<td>"; echo '<a title="'.$row['title_tag']. '" href="' . $row['hyperlink'] . '">' . substr($row['description'], 0, 220) . " . . ." .  '</a>'; echo "</td>";...

It works, but unfortunately this can cut off in the middle of a word. Is there a simple way in the code that I have used above to get it to cut at the next available space or end of word?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Andy R
  • 379
  • 2
  • 5
  • 17

2 Answers2

1
$string = preg_replace("/[^ ]*$/", '', substr($string, 0, $length));

This will cut a string after $length and then cut it to the end of the last word

schnawel007
  • 3,982
  • 3
  • 19
  • 27
1

Save potentially a load of wasted data being pulled out of your database, change your query to :

SELECT .... LEFT(description, 220) as description WHERE .... etc

Then apply the tricks in previous answers using PHP on the string to only show up to the last space.

Cups
  • 6,901
  • 3
  • 26
  • 30
  • How can I do that if I already have a query calling all fields as follows: **SELECT * FROM image_data;** Do I have to list them all individually as **SELECT img, title, left(description, 220) as description FROM image_data**. Is that what you mean? Thanks, Andy ;-) – Andy R Dec 30 '13 at 17:37
  • yes. Unless you really are using all the fields from the table, you should shy away from " select * " – Cups Dec 30 '13 at 19:17