从变量中删除空格以创建有效的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!

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?.