Skip to content

Instantly share code, notes, and snippets.

@joshuapowell
Created November 7, 2011 15:55
Show Gist options
  • Save joshuapowell/1345339 to your computer and use it in GitHub Desktop.
Save joshuapowell/1345339 to your computer and use it in GitHub Desktop.
Convert a string (e.g., News & Events) to a usable CSS selector (e.g., id="news-events", class="news-events").
<?php
/**
* Convert a string (e.g., News &amp; Events) into a usable
* CSS selector (e.g., id="news-events", class="news-events").
*
* @param $text
* @return $text
*/
function check_selector($text) {
// Step 1: remove all uppercase
$text = strtolower($text);
// Step 2: make sure we are not dealing with encoded HTML Special Characters, if so we cannot remove them properly in the next command
$text = htmlspecialchars_decode($text);
// Step 3: replace all non-alphanumeric characters with spaces
$text = preg_replace("/[^a-zA-Z0-9\s]/", ' ', $text);
// Step 4: remove all HTML characters
$text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
// Step 5: replace all spaces with hyphens
$text = str_replace(' ' , '-', $text);
// Step 6: replace multiple-sequential hypens with a single hypen
$text = preg_replace('{\-+}', '-', $text);
// Step 7: return cleaned up text as selector
return $text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment