regex required to clean a string

hi

I have a string say $myString which can contain any case of number, letter, weird character and spacing

I need to do the following:

make it all lower case
replace spaces with -
remove everything that is not a-z 0-9 space . or -
replace multiple instances of - (caused by replacing spaces with -) to just -

So, something like "abcDEF %    %%:@~1  23.jPg" would become "abcdef-1-23.jpg"

full regex and php please
LVL 3
Neil ThompsonSenior Systems DeveloperAsked:
Who is Participating?
 
ddrudikConnect With a Mentor Commented:
$string=strtolower($string);
$string=str_replace(' ','-',$string);
$string=preg_replace('/[^a-z0-9.-]/','',$string);
$string=preg_replace('/-+/','-',$string);
0
 
emphamyCommented:
code attached =)

i spelt it out more there are shorter ways to do it but just wanted to show you the process

as far as removing whitespaces if there are too many spaces you can't really keep removing those without doing a loop, problem is if you do that you are just wasting tons of resources as loops can take a while depending on size of string.  

why not just remove whitespace all together?
<?php
 
$string = "abcDEF %    %%:@~1  23.jPg"
$string = strtolower($string);
$string = str_replace(" ","",$string);
$string = preg_replace('`[^a-z0-9]`i','',$string);
echo $string;
 
?>

Open in new window

0
 
emphamyCommented:
ddrudik beat me to it, as i was submitting i realized that i could have done +- .. good call.
0
 
Neil ThompsonSenior Systems DeveloperAuthor Commented:
Many thanks, worked instantly
0
 
ddrudikCommented:
Thanks for the question and the points.
0
All Courses

From novice to tech pro — start learning today.