I need a one single regex that:
- removes special characters and numbers,
- removes multiple consecutive spaces
- and then snake case the input string.
For example: Open Day - Explore the X-CAMPUS International School in Torino!
Should be turned into: Open_Day_Explore_the_XCAMPUS_International_School_in_Torino
PCRE (PHP<7.3)
I tried with:
([!"£$%&\/\(\)=?'* °#§\-\.,;<>0-9]|\s)
and i got:
OpenDayExploretheXCAMPUSInternationalSchoolinTorino
but i don't know how to apply the snake case.
EDIT(1): i'm not allowed to use multiple regex or functions such as "str_replace".
EDIT(2): the regex is for a tool called make
CodePudding user response:
You can simplify your regex to this: /[^[:alpha:]] /m
This will match every non alpha character.
$re = '/[^[:alpha:]] /m';
$input = 'Open Day - Explore the X-CAMPUS International99 School in Torino!';
$result = preg_replace($re, "_", $input);
$result = trim($result,"_");
echo $result;
// Open_Day_Explore_the_X_CAMPUS_International_School_in_Torino
This basically replaces one or more non alpha char with an underscore, then trims any underscore that might be at the end or beginning of the input.
CodePudding user response:
this seem to work:
([^A-Za-z0-9] )