Forum Moderators: coopster

Message Too Old, No Replies

preg replace question, remove excess characters

         

drooh

9:50 pm on May 17, 2011 (gmt 0)

10+ Year Member



Im using this

$new_file_name = preg_replace('([^a-zA-Z0-9_-])', '_', $file_name);

But sometimes Ill get a renamed file such as

my___name__45.jpg

is there a way to limit it to just 1 underscore?

so that it would be

my_name_45.jpg

I know there is a simple solution for this but im not thinking of it.

drooh

11:22 pm on May 17, 2011 (gmt 0)

10+ Year Member



while(strpos($new_file_name, "__")){
$new_file_name = str_replace("__", "_", $new_file_name);
}

SteveWh

11:30 pm on May 17, 2011 (gmt 0)

10+ Year Member



Might be simplest just to add a line so the end result is

$new_file_name = preg_replace('([^a-zA-Z0-9_-])', '_', $file_name);
$new_file_name = preg_replace('_{2,}', '_', $new_file_name);

I think the code in your second post will also do the same thing.

drooh

2:00 am on May 18, 2011 (gmt 0)

10+ Year Member



Im getting an error with that code

Warning: preg_replace(): No ending delimiter '_' found

SteveWh

7:44 am on May 18, 2011 (gmt 0)

10+ Year Member



Sorry, I forgot the delimiters:

$new_file_name = preg_replace('/[^a-zA-Z0-9_-]/', '_', $file_name);
$new_file_name = preg_replace('/_{2,}/', '_', $new_file_name);