开发者

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

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 st开发者_运维技巧ep??


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


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜