Make sure the string is a valid CSS id name

I have a group of database records (without auto_increment identifiers or something else like that) displayed as a list, and it turns out that I need to distinguish each of them using a unique one id.

I could just add a working counter to the loop and do with it, but, unfortunately, this identifier should be a cross-link to the entire site, however the list is ordered or filtered.

Therefore, I had the idea to include the title of the record as part id(with a prefix so that it does not interfere with layout elements).

How to convert a string to a name idin a reliable way so that it never contains characters that could break HTML or not work as valid CSS selectors?

For instance:

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

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

Thank!

+5
source share
2 answers

I needed a similar solution for Debplink Anchors.

Found to be useful:

function seoUrl($string) {
    //Lower case everything
    $string = strtolower($string);
    //Make alphanumeric (removes all other characters)
    $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
    //Clean up multiple dashes or whitespaces
    $string = preg_replace("/[\s-]+/", " ", $string);
    //Convert whitespaces and underscore to dash
    $string = preg_replace("/[\s_]/", "-", $string);
    return $string;
}

Credit: fooobar.com/questions/99104 / ...

PS: Wordpress users look here: https://codex.wordpress.org/Function_Reference/sanitize_title

+3
source

HTML id. HTML5 . :

<ul class="my-awesome-list">
    <!-- PHP code, begin a for/while loop on rows -->
    <li data-rowtitle="<?php echo json_encode($row["title"]); ?>">
        <?php echo $row["title"]; ?>
    </li>
    <!-- PHP loop end -->
</ul>

jQuery data- * $.fn.data

$(".my-awesome-list li").each(function(){
     var realTitle = $(this).data('rowtitle');
});
0

All Articles