I want to change image names on below conditions
-
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??
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With