1

Can anyone suggest a quick function that will automatically strip spaces & apostrophes from a string in PHP.

I am just need to remove any unwanted stuff from a string before it is used as an email address.

eg.

$email = "myname'[email protected]  "; // need to remove the apostrope & empty space

6 Answers 6

4
echo preg_replace('/[\\\' ]/', '', "myname'[email protected] ");

But I don't believe this is the propper thing to do. Consider something like this:

if(!filter_var("myname'[email protected] ", FILTER_VALIDATE_EMAIL))
    echo("E-mail is not valid");
Sign up to request clarification or add additional context in comments.

3 Comments

Wow.. awesome response thank you guys (and girls) cannot be sexist :-)
Thanks! Also consider the second snippet, because emails can be malformed in so many different ways you cannot predict all of them. It is better to inform user about wrong e-mail or deleting it from the database if you have it already stored.
@Gaz: Also consider ticking the answer. :)
2
$email = str_replace(array("'", ' '), '', $email);

Comments

1

What you need is not str_replace but validation for an email address (what you're describing is actually sanitizing, but wouldn't you want to block the input if the email address is not valid?).

Here's (an example of) a regular expression to check the format of an email address:

( preg_match( '/^\w[-.\w]*@(\w[-._\w]*\.[a-zA-Z]{2,}.*)$/', $_POST['email'] )

Comments

1
$email = "myname'[email protected] ";
$email = preg_replace("/['\s]/", '', $email);

Demo

Comments

1
$remove = array(" ", "'");
$email = str_replace($remove, "", $email);

http://php.net/manual/de/function.str-replace.php

1 Comment

Sorry - i keep forgetting to tick stuff :-) they all work but i've ticked the one i used in the end. Thanks guys much appreciated! :)
1
$email = preg_replace("/(\s|')/", '', "myname'[email protected] ");

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.