phpregexsplit

Split string on a space before one of two whitelisted words


I have strings like this:

wh4tever_(h4r4ct3rs +syMb0|s! ASC
wh4tever_(h4r4ct3rs +syMb0|s! DESC

I don't know what the first characters are, but I know that they end by ' ASC' or ' DESC', and I want to split them so that I get an array like:

array(
    [0] => 'wh4tever_(h4r4ct3rs +syMb0|s!'
    [1] => 'ASC' //or 'DESC'
)

I know it must be absolutely easy using preg_split(), but regexps are something I assumed I'll never get on well with...


Solution

  • You can use the following regular expression with preg_split():

    \s(?=(ASC|DESC))
    

    Explanation:

    Visualization:

    enter image description here

    Complete:

    $str = 'wh4tever_(h4r4ct3rs +syMb0|s! ASC';
    $arr = preg_split('/\s(?=(ASC|DESC))/', $str);
    print_r($arr);
    

    Output:

    Array
    (
        [0] => wh4tever_(h4r4ct3rs +syMb0|s!
        [1] => ASC
    )
    

    Demo