Hi

I'm trying to split a string by comma and semi-colon. Currently I do it like this...

$str = "mail@example.com, mail1@example.com; mail2@example.com;mail3@example.com,";

$mails = preg_split("/;/", $str);

foreach ($mails as $mail){

$temp_mail =  preg_split("/,/", $mail);
if($temp_mail){
	foreach ($temp_mail as $temp_m){
		echo $temp_m . "<br>";	
	} 
} else {
	echo $mail;	
}
}

It works, but is obviously not elegant at all. Is there a way to tell preg_split to split either by comma OR semi-colon? I've played around but haven't figured out how.

Thanks a lot.

H

    Might this do the trick instead?

    $str = "mail@example.com, mail1@example.com; mail2@example.com;mail3@example.com,"; 
    
    // replace ; with , then make and array
    $mails = str_replace(';', ',', $str);
    $mails = explode(',', $mails);
    
    foreach ($mails as $mail) { 
    
    // i think we may need to trim
    echo trim($mail) . '<br />';
    
    }
    

      merci!

      That's clever. I think I'll do exactly that.

      Would still be good, just out of interest, if someone knew whether it's possible with preg_split().

        I don't often use preg_split but it appears that is a good approach as well. Except that you have to do it twice. 😉

          Hi Hagen,

          the point with regular expression pattern actually is that you can define "wildcards" that mean this or that character (or a bunch of characters), e.g. [,;] for a comma or semicolon.

          But still, for your purpose vaaaska's example looks easy and efficient.

            Write a Reply...