Skip to main content

It seems like every part of a website needs to be dynamic. Dynamic, database-driven pages, dynamic JavaScript, dynamic CSS, etc. All this dynamism can make it difficult to style or script a page easily. One way I've learned to combat the rigidness of using CMS' is to give the BODY element a unique ID based on the URL. Doing so allows me to add special styling to any page.

View full article...

<?php

/*
  ID Your HTML Body Using PHP
  Article: http://davidwalsh.name/id-body-php
*/

function generate_id($uri)
{
    /* regular expressions */
    $regex1 = '/[^a-zA-Z0-9]/'; //remove anything but letters and numbers
    $regex2 = '/[\-]+/'; //remove multiple "-"'s in a row
    $regex3 = '/^[-]+/'; //remove starting "-"
    $regex4 = '/[-]+$/'; //remove ending "-"

    /* return... */
    return preg_replace(array(
        $regex1,
        $regex2,
        $regex3,
        $regex4
    ), array(
        '-',
        '-',
        '',
        ''
    ), $_SERVER['REQUEST_URI']);
}

/* do it! */
$body_id = generate_id($_SERVER['REQUEST_URI']);

// NOTE: The above code uses preg_replace to find "bad" or repeated characters and
// replace them with dashes or nothing. I don't claim to be a regular expression
// genius so there may be a better way to construct the preg_replace
// regex parameters.

// --------------------------------------------
// Let's take a look at some example usages:
// --------------------------------------------

/*
  Use the page URI to build out the body ID, joining the "page name" with
  its directory.
*/

// assuming the page URI is:  /some-directory/deeper/my-page
$body_id = generate_id($_SERVER['REQUEST_URI']);

// returns:  some-directory-deeper-my-page
echo '<body id="', $body_id, '">';

/*
  Use the page URI, including the GET parameters.
*/

// assuming the page URI is:  /some-directory/deeper/my-page?category=mootools
$body_id = generate_id($_SERVER['REQUEST_URI']);

// returns:  some-directory-deeper-my-page-category-mootools
echo '<body id="', $body_id, '">';

/*
  The above shows how a non-search-engine-friendly URL being parsed.
*/

// assuming the page URI is: /some-directory/deeper/my-page.php?category=mootools
$body_id = generate_id($_SERVER['REQUEST_URI']);

// returns:  some-directory-deeper-my-page-php-category-mootools
echo '<body id="', $body_id, '">';

// If you'd like, you can remove the ".php" file extension from the URI.
// - http://davidwalsh.name/php-function-get-file-extension-string
function get_file_extension($file_name)
{
    return substr(strrchr($file_name, '.'), 1);
}

?>