Share and options
ven, 05/07/2010 - 16:11
This PHP code snippet compute nice machine name (i.e. with only alpha numerical characters, keeping inside hyphens) from a formated human readable name.
Useful for some automatic machine name identifiers computing from human readable arbitrary titles, I use it sometime in Drupal modules.
<?php
/**
* Helper that generates a machine name using a provided human readable name.
*
* @param string $human_name
* Human readable name.
*
* @return string
* Machine name cleaned-up of any special chars.
*/
function human_to_machine($human_name) {
return strtolower(preg_replace(array(
'/[^a-zA-Z0-9]+/',
'/-+/',
'/^-+/',
'/-+$/',
), array('-', '-', '', ''), $human_name));
}
?>This is not fail-safe but it will work in most cases (if you give a string without any human readable chars you will get an empty string or a string only with one hypen).
This is also a nice sample of preg_replace() usage.



Ajouter un commentaire