How to change all non-word characters and multiple spaces to '' and then all the space to '-' in one preg_replace ()


I want to change image names below conditions

  • All characters without a word turn into a space and
  • then all spaces turn into -

means that if my image name is: Hello My name is' Kh@n "Mr. .Khan " , then it should be changed to 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 a way to apply both conditions in one step?

+4
source share
4 answers

I find this function output ( Hello_My_name_is-Kh-n_-Mr-_Khan_ ) a little 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

+2
source

preg_replace can accept arrays:

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

This is more eloquent, but I do not think it is more effective. Documents do not indicate the order in which regular expressions are applied. Since space characters are not word characters, a safer version:

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

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); 

Besides,

There is a syntax error in your fragment, you need to avoid a single quote until K

0
source

Can I rename downloaded images? If so, keep in mind ...

  • max char count (should be cut off above something reasonable)
  • non-ASCII characters? (transliterator will be better)
0
source

All Articles