English 中文(简体)
PHP preg_replace()模式,字符串净化
原标题:PHP preg_replace() pattern, string sanitization

我有一个regex电子邮件模式,我想从字符串中删除除模式匹配字符外的所有字符,简而言之,我想清除字符串。。。

我不是正则表达式专家,那么我在正则表达式中缺少什么呢?

<?php

$pattern = "/^([w!#$\%& *+-/=?^`{|}~]+.)*[w!#$\%& *+-/=?^`{|}~]+@((((([a-z0-9]{1}[a-z0-9-]{0,62}[a-z0-9]{1})|[a-z]).)+[a-z]{2,6})|(d{1,3}.){3}d{1,3}(:d{1,5})?)$/i";

$email =  contact<>@domain.com ; // wrong email

$sanitized_email = preg_replace($pattern, NULL, $email);

echo $sanitized_email; // Should be contact@domain.com

?>

图案取自:http://fightingforalostcause.net/misc/2006/compare-email-regex.php(第一个…)

最佳回答

不能同时筛选和匹配。您需要将其分解为一个用于剥离无效字符的字符类和一个用于验证有效地址的匹配正则表达式。

$email = preg_replace($filter, "", $email);
if (preg_match($verify, $email)) {
     // ok, sanitized
     return $email;
}

For the first case, you want to use a negated character class /[^allowedchars]/.
For the second part you use the structure /^...@...$/.

看看PHPs过滤器扩展。它使用const unsigned char allowed_list[]=LOWALPHA HIALPHA DIGIT“!#$%\amp;*+-=?^_{|}~@.[]”;`用于清洁。

还有一个需要验证的怪物:http://gcov.php.net/PHP_5_3/lcov_html/filter/logical_filters.c.gcov.php-但请退出http://www.regular-expressions.info/email.html用于更常见和更短的变体。

问题回答

i guess filter_var php function can also do this functionality, and in a cleaner way. Have a look at: http://www.php.net/manual/en/function.filter-var.php

示例:

 $email = "chris@exam\ple.com";
 $cleanEmail = filter_var($email, FILTER_SANITIZE_EMAIL);  // chris@example.com




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签