phpregexdelimiter

What pattern in preg_split() will split by hyphens, underscores and dots?


I have an array full of strings that may contain one or more underscores, dashes, and periods. I want to split the into the characters separated by the underscores, dashes, and periods. So far I've had success with the underscores and dashes but not the periods.

This works:

$family02 = preg_split('/_|-/', $row['family'], -1, PREG_SPLIT_NO_EMPTY);

When I try...

'/_|-./'
'/_|-\./'
'/_|-|./'

...or ordering the delimiters differently, I get splits on 1 of 3 or 2 of 3, or empty arrays.


Solution

  • Simply use

    preg_split('/[-_.]/', $str)
    

    which means you are splitting by one of -, _, .

    If you want to remove empty groups inside of string, then use

    preg_split('/[-_.]+/', $str)
    

    so multiple determiners apply as one.