6

I have a bunch of database records (without auto_increment IDs or anything else like that) rendered as a list, and it came to pass that I need to differentiate each of them with a unique id.

I could just add a running counter into the loop and be done with it, but unfortunately this ID needs to be cross-referenceable throughout the site, however the list is ordered or filtered.

Therefore I got an idea to include the record title as a part of the id (with a prefix so it doesn't clash with layout elements).

How could I transform a string into an id name in a foolproof way so that it never contains characters that would break the HTML or not work as valid CSS selectors?

For example;

Title ==> prefix_title
TPS Report 2010 ==> prefix_tps_report_2010
Mike's "Proposal" ==> prefix_mikes_proposal
#53: Míguèl ==> prefix_53_miguel

The titles are always diverse enough to avoid conflicts, and will never contain any non-western characters.

Thanks!

Emphram Stavanger
  • 4,158
  • 9
  • 35
  • 63
  • If I get your point: you have some row in a table, for each row you want to generate an HTML list item, and each item should have an unique id (HTML attribute `id` ?), this id should not break your HTML and be a valid CSS selector. Why do you need a such thing, and why are you talking about valid CSS selector ? You can't write *static* CSS selector based on *dynamic* ids. – pomeh May 16 '12 at 13:07
  • pomeh: I need to reference individual list items with jQuery, and it's that much more easier if when printing the list, I have id's set for each item. || Rick: That's... an embarrassingly simple yet awesome solution. – Emphram Stavanger May 16 '12 at 13:16
  • I don't understand the part about "printing the list". Also, can you edit the database schema ? If so, you can add a column which could contains something like `md5( current title + date + random number )`, and the value is determined when the data is inserted in the database – pomeh May 16 '12 at 13:18
  • `echo '
  • '.$row["title].'
  • ';` .. and no, I can't change the DB itself, as it's part of a third party software package, and forwards compatibility could be compromised. – Emphram Stavanger May 16 '12 at 13:23
  • 1
    look at my answer, you don't need to use the ID attribute at all, what do you think ? – pomeh May 16 '12 at 13:36