开发者

string replace (php)

开发者 https://www.devze.com 2023-04-01 07:32 出处:网络
Can anyone suggest a quick function that will automatically strip spaces & apostrophes from a string in 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 ");
0

精彩评论

暂无评论...
验证码 换一张
取 消