确保string是有效的CSS ID名称

Emp*_*ger 5 css php

我有一堆数据库记录(没有auto_increment ID或其他任何类似的东西)呈现为列表,而且我需要用独特的方法来区分它们id.

我可以在循环中添加一个运行计数器并完成它,但不幸的是,这个ID需要在整个站点中交叉引用,但是列表是有序或过滤的.

因此,我有一个想法将记录标题包含在内id(使用前缀,因此它不会与布局元素冲突).

我怎么能id以一种万无一失的方式将字符串转换为名称,以便它永远不会包含会破坏HTML或不能作为有效CSS选择器工作的字符?

例如;

Title ==> prefix_title
TPS Report 2010 ==> prefix_tps_report_2010
Mike's "Proposal" ==> prefix_mikes_proposal
#53: Míguèl ==> prefix_53_miguel
Run Code Online (Sandbox Code Playgroud)

标题总是多种多样,足以避免冲突,并且永远不会包含任何非西方字符.

谢谢!

opt*_*tes 7

我需要一个类似的 Deeplink Anchors 解决方案。

发现这很有用:

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;
}
Run Code Online (Sandbox Code Playgroud)

信用:https : //stackoverflow.com/a/11330527/3010027

PS:Wordpress-用户看这里:https : //codex.wordpress.org/Function_Reference/sanitize_title


pom*_*meh 0

id您根本不需要使用 HTML属性。您可以使用HTML5 data-* 属性来存储用户定义的值。这是一个例子:

<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>
Run Code Online (Sandbox Code Playgroud)

$.fn.data然后,在 jQuery 代码中,您可以使用以下方法访问 data-* 值

$(".my-awesome-list li").each(function(){
     var realTitle = $(this).data('rowtitle');
});
Run Code Online (Sandbox Code Playgroud)