dongmi4809 2013-06-26 02:04
浏览 37
已采纳

从变量中删除空格以创建有效的html元素ID?

I am adding fancybox to the product gallery on Wordpress. I am using the product title as id name for hidden div and href of the thumbnail link. Product titles have spaces in them and that breaks the fancybox.

Solutions I found online only refer to the whitespace in between html elements, and my javascript/regex knowledge is not good enough to derive solution from there.

Here is the code I use to generate the product thumbnails and images:

<div class="entry-post-thumbnail">
            <a class="size-<?php echo $image_size;?> fancybox" href="#image-<?php the_title(); ?>"><?php the_post_thumbnail($image_size); ?></a>
            <div id="image-<?php the_title(); ?>" style="display: none;">
                <?php the_post_thumbnail($post->ID,'full'); ?>
            </div>
</div><!-- .entry-post-thumbnail -->

and here is the outputed code:

<a class="size-product fancybox" href="#image-Product three">
    <img src="[###]/wp-content/uploads/2013/06/product-thumbnail.png" class="attachment-product wp-post-image" alt="Product thumbnail" height="222" width="166"></a>
<div id="image-Product three" style="display: none;">
    <img src="[###]/wp-content/uploads/2013/06/product-thumbnail.png" class="attachment- wp-post-image" alt="Product thumbnail" full="" height="222" width="166">               
    </div>

Any help will be much appreciated!

  • 写回答

1条回答 默认 最新

  • drm30963 2013-06-26 02:15
    关注

    use preg_replace

    <div id="image-<?php preg_replace('/(\s/', '', the_title()); ?>" style="display: none;">
    

    A better regex would be [^A-Za-z0-9\-_:.]. This matches all invalid characters for an html ID according to What are valid values for the id attribute in HTML?.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题