DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Perl: Dirify String

11.29.2006
| 3719 views |
  • submit to reddit
        Clean up a string for creation of a directory named using the string.

my $dir = dirify('The s^#%@$!#! <b>title</b> ever');     # outputs 'The-S-Title-Ever'

sub dirify {
    my $s = shift;

    $s =~ s!<[^>]+>!!gs;            # Remove HTML tags.
    $s =~ s!<!<!gs;

    $s =~ s!&[^;\s]+;!!g;           # Remove HTML entities.
    $s =~ s![^A-Za-z0-9-_ ]! !g;    # Allow only alphanumeric chars.
    $s =~ s!\s+! !g;                # Remove extra spaces.
    $s =~ s!\s$!!g;         
    $s =  lc $s;                    # Convert to lower-case.   
    $s =~ s!(\b.)!\U$1!g;           # Capitalize words (Comment out if you don't need this)
    $s =~ tr! !-!s;                 # Finally, change space chars to dashes.

    return $s;
}