views:

65

answers:

4

Hello All,
I want to change image names on below conditions

  • All non word characters turns into space and
  • then all spaces turns into -

means if my image name is : Hello My name is'Kh@n "Mr. .Khan " then it should be changed into Hello-My-name-is-kh-n-mr-Khan .

i need to use below in two steps,

$old_name ='       Hello       My name is\'Kh@n "Mr. Khan        ';
$space_name = preg_replace('/\W/',' ', $old_name);
$new_name= preg_replace('/\s+/','-', $space_name);

echo $new_name // returns Hello-My-name-is-kh-n-mr-Khan

is there any way to apply both conditions in single step??

+5  A: 

preg_replace can take arrays:

$new_name = preg_replace(array('/\s+/', '/\W/'), array('_', '-'), $old_name);

This is more succinct, but I don't believe it's any more efficient. The docs don't specify an order that the regexps are applied. Since space characters are non-word characters, a safer version is:

$new_name = preg_replace(array('/\s+/', '/[^\s\w]/'), array('_', '-'), $old_name);
outis
A: 

You can use arrays in preg_replace:

$old_name ='Hello       My name is\'Kh@n "Mr. Khan ';
$new_name = preg_replace(array('/\s+/','/\W/'),array('_','-'),$old_name);

Also,

Your snippet has syntax error, you need to escape the single quote before K

codaddict
@codaddict thanks, it was typo
JustLearn
A: 

Is this to rename uploaded images? If so, keep in mind...

  • max char count (should snip it at something sensible)
  • non ASCII chars? (transliterate would be best)
alex
yes this is to be done during image upload
JustLearn
@alex what i needs o take care more??
JustLearn
+1  A: 

I find this function's output (Hello_My_name_is-Kh-n_-Mr-_Khan_)a bit ugly
Here is my approach

$name ='Hello       My name is\'Kh@n "Mr. Khan" ';
$name = preg_replace('/\W/',' ', $name);
$name = trim($name);
$name = strtolower($name);
$name = preg_replace('/\s+/','-', $name);

outputs hello-my-name-is-kh-n-mr-khan

Col. Shrapnel
@col. Sharpnel...Thanks for your great idea, how do we limit the length of name ( only 200 )
JustLearn
@JustLearn you can add substr() function call as well.
Col. Shrapnel