Search code examples
phpregexsplitpreg-split

php preg_split, "nothing to repeat" error


I need to split string with multiple possible delimiters

$output = preg_split( "/(\^|+)/", "54654561^[email protected]" );

-> ("54654561", "[email protected]")

$output = preg_split( "/(\^|+)/", "[email protected]" );

-> ("54654561", "[email protected]")

But this regex "/(\^|+)/" fails: PHP Warning: preg_split(): Compilation failed: nothing to repeat at offset 3 for some reason, however it's based on this answer Php multiple delimiters in explode

this one is working $output = preg_split("/[\^|+]/", "54654561^[email protected]" ); is it the right way to split with multiple delimiters?

edit : sorry I just realized it's working like this $output = preg_split("/(\^|\+)/", "54654561^[email protected]" );


Solution

  • If it's single characters you're trying to match, I would actually opt for the [\^\+] option.

    Demo: http://ideone.com/ftXSS

    The [] syntax is called a character class or character set, and it's designed to do specifically what you need.

    A "character class" matches only one out of several characters. To match an a or an e, use [ae]. You could use this in gr[ae]y to match either gray or grey.

    http://www.regular-expressions.info/quickstart.html