Tuesday, January 24, 2006

PHP clean filename

Clean a string for filename


`echo "$clean" | tr A-Z a-z | tr "[]()&~@#$%^&*()_+=;:,.!' " "-" `;


This programming one liner allows you to clean the unwanted characters in a string. The list of characters is specified as the first parameter to the tr command.


Programming "One Liner" lookup terms:
str_replace tr

USE THIS PROGRAMMING ONE LINER AT OWN RISK AS AUTHOR CLAIMS NO RESPONSIBILITY.
If you would like more information on any of the commands, please feel free to contact me with your . You can also read other posts on programming code, lookup the programming terms displayed above or visit my network security blog. Other external programming blogs on Technorati and programming blogs on Google.

6 comments:

Anonymous said...

Using shell commands is probably the most asinine way of string manipulation in PHP. For Pete's and portability's sake, use native functions:

$str = preg_replace("/[^a-z0-9-]/", "-", strtolower($str));

Anonymous said...

I'm going to have to agree with anonymous here...

unless the shell command runs somewhere around 200x faster than preg_replace then it might be useful in certain situations.

Anonymous said...

I Agreeeee!

Use Anonymous' code


$str = preg_replace("/[^a-z0-9-]/", "-", strtolower($str));

Anonymous said...

$str = preg_replace( "/[^\w_-]/", "-", strtolower( $str ) );

Anonymous said...

aren't we forgetting dots in file names? and "\w" already includes "_".

$str = preg_replace("/[^\w\.-]/", "-", strtolower($str));

Tejuteju said...

It was really a nice article and I was really impressed by reading this Ruby on Rails Online Training India