string replace (php)
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 stu开发者_如何转开发ff from a string before it is used as an email address.
eg.
$email = "myname's@site.com "; // need to remove the apostrope & empty space
echo preg_replace('/[\\\' ]/', '', "myname's@site.com ");
But I don't believe this is the propper thing to do. Consider something like this:
if(!filter_var("myname's@site.com ", FILTER_VALIDATE_EMAIL))
echo("E-mail is not valid");
$email = str_replace(array("'", ' '), '', $email);
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'] )
$email = "myname's@site.com ";
$email = preg_replace("/['\s]/", '', $email);
Demo
$remove = array(" ", "'");
$email = str_replace($remove, "", $email);
http://php.net/manual/de/function.str-replace.php
$email = preg_replace("/(\s|')/", '', "myname's@site.com ");
精彩评论