0

I have a variable within PHP coming from a form that contains email addresses all separated by a comma (') For example: [email protected],[email protected],[email protected],[email protected]

What I am trying to achieve is to look at the variable, find for example @domain2.com and remove everything between the comma that are either side of that email.

I know I can use str_replace to replace just the text I'm after, like so:

$emails=str_replace("@domain2.com", "", "$emailscomma");

However, I'm more looking to remove that entire email based on the text I'm asking it to find.

So in this example I'm wanting to remove [email protected] and [email protected]

Is this possible?

Searched any articles I could find but couldn't find something that finds something and then replaces but more than just the text it finds.

1
  • 1
    You need regular expressions. Look into preg_replace. Commented Dec 16, 2020 at 14:41

1 Answer 1

1

You can of course use regular expressions, but I would suggest a bit easier way. Operating on arrays is much easier than on strings and substrings. I would convert your string to an array and then filter it.

$emails = "[email protected],[email protected],[email protected],[email protected]";

// Convert to array (by comma separator)
$emailsArray = explode(',', $emails);

$filteredArray = array_filter($emailsArray, function($email) {
    // filters out all emails with '@domain2.com' substring
    return strpos($email, '@domain2.com') === false;
});

print_r($filteredArray);

Now you can convert the filtered array to string again. Just use implode() function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.