Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 step??

like image 791
JustLearn Avatar asked Feb 27 '23 04:02

JustLearn


1 Answers

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);
like image 113
outis Avatar answered May 01 '23 06:05

outis