Page 1 of 1

remove comma from end of loop

Posted: Sat Nov 29, 2014 6:27 pm
by cjkeane
Hi everyone.

I have a list of emails in a string. i strip off the names and brackets then separate each by a comma. the issue i'm having is that an extra comma is added to the end of the loop. any suggestions are welcome.

Another thing. I'm finding that I need to echo the result of $emails within the loop. if i echo it outside the loop, nothing displays.

Code: Select all

<?php
        if (!empty($toaddress)) {
		$toaddress = strtolower($toaddress);
		$pattern="/(?:[a-z0-9!#$%&'*+=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/";
		preg_match_all($pattern, $toaddress, $matches);
		foreach($matches[0] as $email){
			$emails = $email .',' ;
                        //echo $emails; 
		 }										
		echo implode(", ", $emails);
	}
?>

Re: remove comma from end of loop

Posted: Sat Nov 29, 2014 6:40 pm
by Celauran
Don't do this.

Code: Select all

foreach($matches[0] as $email){
                        $emails = $email .',' ;
Add the emails to a new array instead, then implode.

Re: remove comma from end of loop

Posted: Sat Nov 29, 2014 6:47 pm
by cjkeane
Celauran wrote:Don't do this.

Code: Select all

foreach($matches[0] as $email){
                        $emails = $email .',' ;
Add the emails to a new array instead, then implode.
thanks. sorry. i misread your reply. i'll give that a try and get back to you.

this seems to work:

Code: Select all

if (!empty($toaddress)) {
	foreach($matches[0] as $email){
	        $newArray[] = $email;
	 }										
        echo implode(", ", $newArray);
}

Re: remove comma from end of loop

Posted: Sat Nov 29, 2014 6:52 pm
by Celauran
cjkeane wrote:however that is what i already have.
No it's not.

Also, wait. $matches[0] is already an array? Just implode.

Code: Select all

$emails = implode(',', $matches[0]);

Re: remove comma from end of loop

Posted: Sat Nov 29, 2014 7:03 pm
by cjkeane
Celauran wrote:
cjkeane wrote:however that is what i already have.
No it's not.

Also, wait. $matches[0] is already an array? Just implode.

Code: Select all

$emails = implode(',', $matches[0]);
your suggestion works too. thanks!