hey. I need to make file names be consisted of only numbers and letters. Like if there is an image named 'img*1L%^_ove>ly.jpg' it will become 'img1Lovely.jpg' . Only digits and letters (btw letters meaning even if not english letters). Thanks a lot. I went through php.net, failed finding sth like this. Maybe you profies know) or can advise me easy way to do it.

Recommended Answers

All 4 Replies

all you need to do is use preg_replace() to remove the unwanted set of characters.

//your initial string
$str = 'img*1L%^_ove>ly.jpg';

/*
//this removes anything that is NOT
//a,b,c,....z
//A,B,C,...Z
//0,1,2,...9
//In other words, it KEEPS only a-z, A-Z, and 0-9. 
//If you want other character(s), simply add 
//it(them) immediately after the "9"
*/
$str = preg_replace('#[^a-zA-Z0-9]#','',$str);

all you need to do is use preg_replace() to remove the unwanted set of characters.

//your initial string
$str = 'img*1L%^_ove>ly.jpg';

/*
//this removes anything that is NOT
//a,b,c,....z
//A,B,C,...Z
//0,1,2,...9
//In other words, it KEEPS only a-z, A-Z, and 0-9. 
//If you want other character(s), simply add 
//it(them) immediately after the "9"
*/
$str = preg_replace('#[^a-zA-Z0-9]#','',$str);

ok this would work but is there another way so that i wouldnt deal with regular expressions?

without regex, the alternative is to list ALL the characters you don't want and use str_replace() to remove them - ex assuming you do not want any of the following:
# _ -

then use:

$str=str_replace('#_-','',$str);
echo $str;

but it is easier if you list only the ones that you DO want and use a regex to do the filtering.

without regex, the alternative is to list ALL the characters you don't want and use str_replace() to remove them - ex assuming you do not want any of the following:
# _ -

then use:

$str=str_replace('#_-','',$str);
echo $str;

but it is easier if you list only the ones that you DO want and use a regex to do the filtering.

tanks:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.