user6079755
user6079755

Reputation:

PHP Remove email addresses from comma separated string

I'm trying to delete the email from a comma separated string. I have a script that brings me emails. Any way to do this quickly:

$cadena = "[email protected],0001,00005,0010,[email protected],003";

$cadena = explode(",", $cadena);        

foreach($cadena as $res){
    if(filter_var($res, FILTER_VALIDATE_EMAIL)){
        $result[] = $res;
    }
}

Result:

array([email protected],[email protected]);

But I need:

string "0001,00005,0010,003"

Upvotes: 0

Views: 207

Answers (2)

Don't Panic
Don't Panic

Reputation: 41810

If you can count on all the other stuff in the string being like it is in your example, instead of trying to find and remove emails, you can filter it with is_numeric.

$result = implode(',', array_filter(explode(',', $cadena), 'is_numeric'));

If the values you want to keep just happen to be numeric in your example, never mind.

Upvotes: 1

AbraCadaver
AbraCadaver

Reputation: 78994

You are adding to your result array if it DOES validate as an email, so change it to add if it DOES NOT ! validate:

$cadena = explode(",", $cadena);        

foreach($cadena as $res){
    if(!filter_var($res, FILTER_VALIDATE_EMAIL)){
        $result[] = $res;
    }
}

Then just implode() it:

$result = implode(',', $result);

Upvotes: 4

Related Questions